Programing

이벤트를 한 번만 바인딩

lottogame 2020. 8. 19. 22:28
반응형

이벤트를 한 번만 바인딩


다음 코드가 있습니다.

function someMethod()
{
  $(obj).click(function {});
}

someMethod는 두 번 호출되므로 클릭 이벤트가 두 번 바인딩됩니다. 한 번만 바인딩하려면 어떻게해야합니까?


적용 할 수 있다면 아마도 event.preventDefaultevent.stopPropagation을 살펴 보거나 다음같은 방법 내에서 매번 바인딩 해제 및 바인딩을 원할 것입니다.

function someMethod()
{
  $(obj).off('click').on('click', function(e) {
    // put your logic in here 
  });
}

pna의 답변 외에도 실수로 모든 클릭 이벤트의 바인딩을 해제하지 않도록 이벤트 네임 스페이스에 대해 생각할 수 있습니다.

function someMethod () {
    $ (obj) .unbind ( 'click.namespace'). bind ( 'click.namespace', function () {});
}

https://api.jquery.com/event.namespace/


이 특정 함수를 이미 바인딩했는지 확인하는 기본 제공 방법이 없습니다. 여러 클릭 기능을 개체에 바인딩 할 수 있습니다. 예를 들면 :

$('#id').bind('click', function(){
alert('hello');
});


$('#id').bind('click', function(){
alert('goodbuy');
});

개체를 클릭 할 때 위의 작업을 수행하면 안녕, 작별 인사를 경고합니다. 하나의 함수 만 클릭 이벤트에 바인딩되었는지 확인하려면 클릭 이벤트 처리기를 바인딩 해제 한 다음 다음과 같이 원하는 함수를 바인딩합니다.

$(obj).unbind('click').bind('click', function(){... });

확실한 해결책은 전화하지 않는 것입니다. someMethod() 두 번 입니다. 그것을 고칠 수 없다면 상태 변수를 유지할 수 있으므로 다음과 같이 한 번만 바인딩됩니다.

function someMethod()
{
    if (!someMethod.bound) {
        $(obj).click(function() {});
        someMethod.bound = true;
    }
}

참고 : 이것은 바인딩 여부를 추적하기 위해 전역 변수를 도입하는 대신 함수 자체의 속성을 사용합니다. 객체 자체에 대한 속성을 사용할 수도 있습니다.

여기에서 작동하는 것을 볼 수 있습니다 : http://jsfiddle.net/jfriend00/VHkxu/ .


또는 on ()과 유사한 jQuery의 one () 함수를 사용하지만 여러 번 바인딩하더라도 이벤트는 한 번만 발생합니다.

http://api.jquery.com/one/


jQuery를 사용하면 한 번만 매우 쉽게 일부 함수를 호출 할 수 있습니다.

function someMethod()
{

     $(obj).click(function() {});
      this.someMethod = $.noop;
}

나는 당신의 논리를 모르기 때문에 이것은 제안입니다. 당신을 위해 작동하거나 작동하지 않을 수 있습니다.

jquery live () 및 one () 함수를 결합하면 이벤트 리 바인드보다 더 나은 결과를 얻을 수 있습니다.

두 개의 DOM 요소 (상위 및 하위)가있는 경우 특수한 경우가 작동합니다. 부모 노드의 Live ()는 이벤트가 호출되는지 확인한 다음 one ()을 호출하여 한 번만 실행되는 이벤트를 동적으로 등록합니다. (이것은 리 바인드와 같은 유사한 기능을 제공합니다).


var bound = false;

function someMethod()
{
    if(!bound)
    {
       $(obj).click(function {});
       bound = true;
    }
}

그러나 나는 아마도 어떤 종류의 해결 방법을 만들기 전에 두 번 호출되는 이유를 조사 할 것입니다.


객체에 한 번만 바인딩하려면 플래그를 구현하고 해당 객체에 고정해야합니다.

예를 들면 :

if($('#id') && $('#id').data('done') == null)) {
    $('#id').bind('click', function() {
        alert('hello');
    });

    $('#id').data('done', true);
}

바인딩 된 요소에 css 클래스를 추가 한 다음 필터링 할 수 있습니다.

function someMethod()
{
    $(obj).not('.click-binded')
          .click(function {})
          .addClass('click-binded');
}

이 방법은 플러그인에도 사용할 수 있습니다.

  $(obj).not('.datetimepicker-applied')
        .datetimepicker()
        .addClass('datetimepicker-applied');

You can use this jQuery extension function.

$.fn.once = function (type, fn, uid) {
  if(uid == undefined) {
    console.error("Called $.once without uid\n", this, "\n", fn);
  }

  var dataStr = type+"-handler-"+uid;
  if(!this.data(dataStr)) {
    this.data(dataStr, true);
    this.on(type, fn);
  }
};

Instead of doing this

$("button").on("click", function(){
  alert("You Clicked On A Button");
});

Ya do this

$("button").once("click", function(){
  alert("You Clicked On A Button");
}, "btnHandler");

Now when I have a function around it

function addBtnHandler() {
  $("button").once("click", function() {
    alert("You Clicked On A Button");
  }, "btnHandler");
}

And I call it multiple times

addBtnHandler();
addBtnHandler();
addBtnHandler();

It only does it once.

Notice that the extension works by checking both uid and type. This means that you can bind different types of handlers with the same uid, you may or may not want this. To change it edit.

var dataStr = type+"-handler-"+uid;

With something like

var dataStr = "handler-"+uid;


I was also trying to use off and on method of jquery for binding event only once with the dom element which does not exists yet or the dom element is not yet created.

$('.select').off('event').on('event', 'selector', function(e){ // });

This code was not working properly

I came across a very lucrative method that is 'one' method. It is very useful when you want to bind an event only once.

You can find the document here http://api.jquery.com/one/

This is same as method 'on' but different with its behavior with not to stick with the event for multiple selectors.

$('body').one('click', 'selector', function(){ // do your stuff here });

You can achieve this with pure JS, using addEventListener method and his once option

target.addEventListener('click', handler, {once: true});

참고URL : https://stackoverflow.com/questions/8408826/bind-event-only-once

반응형