old/Javascript

[JQuery] .one() 함수, 이벤트 한 번만 적용(사용)하기

뒷골목프로그래머 2020. 1. 29. 20:35
반응형

안녕하세요. 글쓰는 개발자입니다.

오늘은 JQuery의 .one() 함수를 소개하고자 합니다.

저를 몇날 몇일간 괴롭혔던 검색제시어 영역 이외 클릭시 제시어 창 닫힘 및 입력값 초기화 기능 문제를 해결해준 고마운 기능입니다.

 

아래 내용에 대한 설명은 https://api.jquery.com/one/를 참고했습니다.

 

.one() | jQuery API Documentation

Description: Attach a handler to an event for the elements. The handler is executed at most once per element per event type. The .one() method is identical to .on(), except that the handler for a given element and event type is unbound after its first invo

api.jquery.com

 

1. 사용배경

 JQuery의 .on() 함수를 사용했으며, 이벤트가 지속적으로 발생하였음. 따라서, 이벤트 종료를 위해

  1. event.preventDefault();

  2. event.stopPropagation();

  3. event.stopImmediatePropagation();

  4. return false;

위의 4가지를 사용해봤지만 이벤트가 종료되지 않았음.

 

2. 해결방법

   .one() 및 on()함수를 쓰되 .off(event)를 추가하는 두 가지 방식을 확인할 수 있었습니다. 저는 업무에서 .one()을 사용했지만 두가지 모두 소개하겠습니다. 버튼을 클릭하게되면 보통의 click 이벤트는 지속적으로 이벤트가 적용되지만 아래 예제의 경우 한 번만 적용됨을 확인하실 수 있습니다.

 

.one() 함수 사용

<button type="button" id="oneClickTest">oneClick</button>

<script>
  $( "#oneClickTest" ).one( "click", function( event ) {
	  alert( "This will be displayed only once." );
  });
</script>

.on() 함수 사용 및 $(this).off(event) 추가

<button type="button" id="onClickTest">onClick</button>

<script>
  $( "#onClickTest" ).on( "click", function( event ) {
  	alert( "This will be displayed only once." );
  	$( this ).off( event );
  });
</script>

 

3. 실제 업무 적용 예시

//영역 밖 클릭시 초기화[S]
$("body").one("click", function(e){

  if((e.target).attr("class") != 'test'){
  	console.log("영역 밖");
  }         

});

scirpt단을 작업하시면서, 이벤트를 한 번만 사용해야 할 경우가 종종 있으실 텐데 유용하게 사용하시길 바라겠습니다.

 

반응형