Programming

클릭 이벤트가 이미 바인딩되어 있는지 확인하는 방법-JQuery

procodes 2020. 7. 5. 21:28
반응형

클릭 이벤트가 이미 바인딩되어 있는지 확인하는 방법-JQuery


클릭 이벤트를 버튼으로 바인딩하고 있습니다.

$('#myButton').bind('click',  onButtonClicked);

하나의 시나리오에서 이것은 여러 번 호출되므로, 내가 할 때 trigger여러 개의 ajax 호출을 방지하고 싶습니다.

bind이전에 묶이지 않은 경우에만 어떻게합니까?


업데이트 : 2012 년 8 월 24 일 : jQuery 1.8에서는 더 이상을 사용하여 요소의 이벤트에 액세스 할 수 없습니다 .data('events'). (자세한 내용은 이 버그 를 참조하십시오.) jQuery._data(elem, 'events')내부 데이터 구조 를 사용하여 동일한 데이터에 액세스 할 수 있습니다. 문서 구조는 문서화되지 않았으므로 100 % 안정적으로 유지되지는 않습니다. 그러나 이것은 문제가되어서는 안되며, 위의 플러그인 코드의 관련 줄을 다음과 같이 변경할 수 있습니다.

var data = jQuery._data(this[0], 'events')[type];

jQuery 이벤트는이라는 데이터 객체에 저장 events되므로 다음을 검색 할 수 있습니다.

var button = $('#myButton');
if (-1 !== $.inArray(onButtonClicked, button.data('events').click)) {
    button.click(onButtonClicked);
}

물론이 코드가 한 번만 호출되도록 응용 프로그램을 구성 할 수 있다면 가장 좋습니다.


이것은 플러그인으로 캡슐화 될 수 있습니다 :

$.fn.isBound = function(type, fn) {
    var data = this.data('events')[type];

    if (data === undefined || data.length === 0) {
        return false;
    }

    return (-1 !== $.inArray(fn, data));
};

그런 다음 전화를 걸 수 있습니다.

var button = $('#myButton');
if (!button.isBound('click', onButtonClicked)) {
    button.click(onButtonClicked);
}

한 가지 더 방법-CSS 버튼 및 필터로 이러한 버튼을 표시하십시오.

$('#myButton:not(.bound)').addClass('bound').bind('click',  onButtonClicked);

최근에 jQuery를 버전은 대체 bind와 함께 on:

$('#myButton:not(.bound)').addClass('bound').on('click',  onButtonClicked);

jQuery 1.7 이상을 사용하는 경우 :

당신은 off전에 전화 할 수 있습니다 on:

$('#myButton').off('click', onButtonClicked) // remove handler
              .on('click', onButtonClicked); // add handler

그렇지 않은 경우 :

첫 번째 이벤트를 바인딩 해제 할 수 있습니다.

$('#myButton').unbind('click', onButtonClicked) //remove handler
              .bind('click', onButtonClicked);  //add handler

내가 보는 가장 좋은 방법은 live () 또는 delegate ()를 사용하여 각 자식 요소가 아닌 부모에서 이벤트를 캡처하는 것입니다.

버튼이 #parent 요소 안에 있으면 다음을 교체 할 수 있습니다.

$('#myButton').bind('click', onButtonClicked);

으로

$('#parent').delegate('#myButton', 'click', onButtonClicked);

이 코드가 실행될 때 #myButton이 아직 없더라도.


나는 "한 번"이라는 아주 작은 플러그인을 작성했습니다. 요소에서 off 및 on을 실행하십시오.

$.fn.once = function(a, b) {
    return this.each(function() {
        $(this).off(a).on(a,b);
    });
};

And simply:

$(element).once('click', function(){
});

Here's my version:

Utils.eventBoundToFunction = function (element, eventType, fCallback) {
    if (!element || !element.data('events') || !element.data('events')[eventType] || !fCallback) {
        return false;
    }

    for (runner in element.data('events')[eventType]) {
        if (element.data('events')[eventType][runner].handler == fCallback) {
            return true;
        }

    }

    return false;
};

Usage:

Utils.eventBoundToFunction(okButton, 'click', handleOkButtonFunction)

Based on @konrad-garus answer, but using data, since I believe class should be used mostly for styling.

if (!el.data("bound")) {
  el.data("bound", true);
  el.on("event", function(e) { ... });
}

Why not use this

unbind() before bind()

$('#myButton').unbind().bind('click',  onButtonClicked);

To avoid to check/bind/unbind, you can change your approach! Why don't you use Jquery .on() ?

Since Jquery 1.7, .live(), .delegate() is deprecated, now you can use .on() to

Attach an event handler for all elements which match the current selector, now and in the future

It means that you can attach an event to a parent element that is still existing and attach children elements whether they are present or not!

When you use .on() like this:

$('#Parent').on('click', '#myButton'  onButtonClicked);

You catch event click on parent and it search child '#myButton' if exists...

So when you remove or add a child element, you do not have to worry about whether to add or remove the event binding.


Try:

if (typeof($("#myButton").click) != "function") 
{
   $("#myButton").click(onButtonClicked);
}

if ($("#btn").data('events') != undefined && $("#btn").data('events').click != undefined) {
    //do nothing as the click event is already there
} else {
    $("#btn").click(function (e) {
        alert('test');
    });
}

As of June 2019, I've updated the function (and it's working for what I need)

$.fn.isBound = function (type) {
    var data = $._data($(this)[0], 'events');

    if (data[type] === undefined || data.length === 0) {
        return false;
    }
    return true;
};

JQuery has solution:

$( "#foo" ).one( "click", function() {
  alert( "This will be displayed only once." );
}); 

equivalent:

$( "#foo" ).on( "click", function( event ) {
  alert( "This will be displayed only once." );
  $( this ).off( event );
});

참고URL : https://stackoverflow.com/questions/6361465/how-to-check-if-click-event-is-already-bound-jquery

반응형