简体   繁体   中英

Test if event handler is bound to an element in jQuery by delegate() method

I have a question similar to this one , however there is one important difference. The method provided in the accepted answer works properly with "directly" bound events. It does not produce results if the handlers are assigned with the delegate method. For example:

$("#some-element").delegate(".some-class", "click", function () {
  alert("Click!");
});

After elements with class some-class are generated and inserted into the html, is there a way to test if the click event handler has been bound to them?

EDIT: As per @Pointy's comment I'll correct the question above, since the handler wouldn't be bound to .some-class :

Is there a way to check if an element, represented, for instance, by a jQuery object (in this example it could be $(".some-class") ), if clicked, would trigger the handler?

As pointed out by Pointy the events bubble up and there is single "master" event handler bound to the root element which checks if the element which initially received the click has the class you provided, if it does, your callback will be called.

So to check if your callback is going to be called on the element all you have to do is to check if the element is in the list provided by selector $("#some-element .some-class");

So something like this should work (haven't tested):

var testEl = elementYouWantToTestAgainst;
if ($("#some-element .some-class").is(testEl)) {
    //It is "bound"
}

Or another solution, which does the same thing;

//Which should do something like this:  
var els = $("#some-element .some-class");
els.each(function() {
    if (this === testEl) {
        //It is "bound"
    }
});

As for debugging events, I usually just add console.log("Event fubar fired!"); to the handlers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM