Svelte

[Svelte]7가지 이벤트 수정자

DevStory 2022. 8. 8.

이벤트 수정자

Svelte에서 이벤트 리스너는 다음 방식으로 추가할 수 있습니다.

<script>
  function handleClickMethod1(event) {
    console.log('함수 선언문');
    console.log(event);
  };

  const handleClickMethod2 = function(event) {
    console.log('함수 표현식');
    console.log(event);
  }

  const handleClickMethod3 = (event) => {
    console.log('화살표 함수');
    console.log(event);
  }
</script>

<button on:click={handleClickMethod1}>
  함수 선언문
</button>

<button on:click={handleClickMethod2}>
  함수 표현식
</button>

<button on:click={handleClickMethod3}>
  화살표 함수
</button>

<button 
  on:click={(event) => {
    console.log('익명 함수');
    console.log(event);
  }}>
  익명 함수
</button>

DOM API 내부적으로 addEventListener() 함수가 호출됩니다.

 

addEventListener() 함수에는 세 가지 매개변수가 존재합니다.

- 첫 번째 매개변수는 이벤트 타겟(해당 이벤트가 동작하는 타겟)

- 두 번째 매개변수는 리스너(해당 이벤트가 동작하면 호출되어야 하는 함수)

- 세 번째 매개변수는 option(이벤트 수정자)으로 생략 가능

 

Svelte에서 addEventListener() 함수에 이벤트 수정자를 전달하기 위해서는 on 지시자를 사용합니다.


preventDefault

form 데이터 제출 방지, 끌어서 놓기 등.. 이러한 동작을 방지하기 위해 이벤트 객체에서 preventDefault() 함수를 호출할 수 있습니다.

<script>
  const onClick = (event) => {}
  
  const handleClickMethod = (event) => {
    event.preventDefault();
    onClick(event);
  }
</script>

<button on:click={handleClickMethod}>
  버튼
</button>

Svelte에서는 preventDefault 수정자를 on 지시자에서 설정할 수 있습니다.

<script>
  const handleClickMethod = (event) => {}
</script>

<button on:click|preventDefault={handleClickMethod}>
  버튼
</button>

stopPropagation

이벤트 캡처/버블링 과정이 부모(다음 단계)로 전달되지 않도록 하기 위해 이벤트 객체에서 stopPropagation() 함수를 호출할 수 있습니다.

<script>
  const onClick = (event) => {}
  
  const handleClickMethod3 = (event) => {
    event.preventDefault();
    onClick(event);
  }
</script>

<button on:click={handleClickMethod}>
  버튼
</button>

Svelte에서는 stopPropagation 수정자를 on 지시자에서 설정할 수 있습니다.

<script>
  const handleClickMethod = (event) => {}
</script>

<button on:click|stopPropagation={handleClickMethod}>
  버튼
</button>

passive

passvie 수정자는 웹 브라우저에서 버벅거리는 스크롤을 최적화하고 싶을 때 사용됩니다. Chrome에서는 기본적으로 passive를 생성합니다. 즉, passive의 값이 true입니다.

<script>
  import { onMount } from "svelte";

  const onScroll = (event) => {}

  let element;

  onMount(() => {
    element.addEventListener('scroll', onScroll, {passive: true});

    return () => {
      element.removeEventListener('scroll', onScroll, {passive: true});
    }
  });
</script>

<div bind:this={element} />

Svelte에서는 passive 수정자를 on 지시자에서 설정할 수 있습니다.

<script>
  const onScroll = (event) => {}
</script>

<div bind:scroll|passive={element} />

nonpassive

반대로 passive 수정자의 값을 설정하지 않으려면 false로 설정합니다.

<script>
  import { onMount } from "svelte";

  const onScroll = (event) => {}

  let element;

  onMount(() => {
    element.addEventListener('scroll', onScroll, {passive: false});

    return () => {
      element.removeEventListener('scroll', onScroll, {passive: false});
    }
  });
</script>

<div bind:this={element} />

Svelte에서는 nonpassive 수정자를 on 지시자에 설정함으로써 passive를 false로 설정합니다.

<script>
  const onScroll = (event) => {}
</script>

<div bind:scroll|nonpassive={element} />
반응형

once

이벤트 리스너가 한 번만 호출되고 즉시 제거하고 싶은 경우 once 수정자를 사용합니다. on 지시자를 사용하지 않는다면 다음 소스 코드처럼 이벤트 리스너를 설정해야 합니다.

<script>
  import { onMount } from "svelte";

  const handleClickMethod = (event) => {}

  let element;

  onMount(() => {
    element.addEventListener('click', handleClickMethod, {once: true});

    return () => {
      element.removeEventListener('click', handleClickMethod, {once: true});
    }
  });
</script>

<button bind:this={element}>
  버튼
</button>

컴포넌트가 DOM에 추가될 때, 실행되는 생명주기 함수 onMount()를 사용하여 이벤트 리스너를 추가합니다. onMount() 함수의 return문에는 이벤트 리스너를 제거합니다.

 

Svelte에서는 once 수정자를 on 지시자에서 설정함으로써 코드를 간결하게 구현할 수 있습니다.

<script>
  const handleClickMethod = (event) => {
  }
</script>

<button on:click|once={handleClickMethod}>
  버튼
</button>

capture

캡처 단계(상위 요소에서 하위 요소로 이벤트 전파 방식)에 대한 이벤트 리스너를 등록하려는 경우 capture 수정자를 사용합니다.

<script>
  import { onMount } from "svelte";

  const handleClickMethod = (event) => {}

  let element;

  onMount(() => {
    element.addEventListener('click', handleClickMethod, {capture: true});

    return () => {
      element.removeEventListener('click', handleClickMethod, {capture: true});
    }
  });
</script>

<button bind:this={element}>
  버튼
</button>

Svelte에서는 capture 수정자를 on 지시자에서 설정할 수 있습니다.

<script>
  const handleClickMethod = (event) => {}
</script>

<button on:click|capture={handleClickMethod}>
  버튼
</button>

self

이벤트 리스너가 이벤트가 자기 자신일 때만 호출되고 하위 요소에서 호출되지 않기를 원하는 경우 self 수정자를 사용합니다.

<script>
  const onClick = (event) => {}
  
  let element;
  function handleClickMethod(event) {
    if (event.target === element) {
      onClick(event);
    }
  }
</script>

<button bind:this={element} on:click={handleClickMethod}>
  버튼
</button>

Svelte에서는 self 수정자를 on 지시자에서 설정할 수 있습니다.

<script>
  const handleClickMethod = (event) => {}
</script>

<button on:click|self={handleClickMethod}>
  버튼
</button>

이벤트 수정자 연결

이벤트 처리 함수에 1개 이상의 이벤트 수정자를 적용하려는 경우 원하는 만큼 이벤트 수정자를 연결할 수 있습니다.

<script>
  const handleClickMethod = (event) => {
  }
</script>

<button on:click|once|stopPropagation|preventDefault={handleClickMethod}>
  버튼
</button>

단, 다음 소스 코드처럼 passive 수정자와 preventDefault 수정자를 함께 연결할 수 없습니다.

<script>
  const handleClickMethod = (event) => {
  }
</script>

<button on:click|passive|preventDefault={handleClickMethod}>
  버튼
</button>
반응형

댓글