views:

85

answers:

1

Using:

$('#foo').data('events').click

We are able to access an iterative object of click handlers added to the element '#foo' but only when they were added with .bind()

Is there a way to get the handlers for an event added with .live()?

Is there any other way to know if an element has a click handler assigned?

+2  A: 

live events are added to the document. Use

$(document).data('events').click

The above will return an array of objects containing information about each bound click handler. Each of these objects has a selector property containing the selector that was used at the time of binding with $(selector).live(.., ..).

Any of these selectors that matches the element with id foo will get triggered when #foo is clicked. Note that the selector does not have to be exactly #foo for that to happen. There are many other selectors that can be used to target an element. For example if #foo was a <p>, then a live click handler such as

$("p").live("click", function..)

will also target #foo.

Here's one approach. Loop through each object, and see if any of the elements matching the selector property include #foo.

var handlers = $(document).data('events').click;

// jQuery quirk: $.map callback takes arguments (obj, index) and
// $(..).map takes callback arguments as (index, obj)
var fooClickHandlers = $.map(handlers, function(handler) {
    if($(handler.selector).is('#foo')) {
        return handler;
    }
    return null;
});

// fooClickHandlers is a list of all handlers that will fire on #foo click
Anurag
Great, but how do we know which of those handlers will fire when '#foo' is clicked?Thank you.
Anderson De Andrade
@Anderson .. updated the answer for your comment.
Anurag