Once an event is bound in jQuery, how do you get a reference to an event handler function?

If I attach a click event handler:

$(".selector").bind("click", function () {
  // some handler function
});

How can I get a link to this function? This does not work:

var refToFunc = $(".selector").bind("click");
typeof refToFunc === "object";  // I want the function

I think that bind("eventname")in this case it simply returns a jQuery object, not an event handler function. It must be saved somewhere.

+6
source share
3 answers

Very interesting question. You can get it as follows:

var refToFunc = $(".selector").data("events")["click"][0].handler;

Please note that we used [0]it because you have an array of handlers if you linked more than one handler. For other events, just change the name of the event.

, ( ):

$.fn.getEventHandlers = function(eventName){
  var handlers = [];
  this.each(function(){
     $.each($(this).data("events")[eventName], function(i, elem){
         handlers.push(elem.handler);    
     });     
  });
  return handlers;
};

?:

$(".selector").getEventHandlers("click");

, .

:

var refToFunc = $(".selector").getEventHandlers("click")[0];

, .

+6

, data. :

$('.selector').data('events').click[0].handler;

, click .


, . .

var handler = function() {
    // some content
});

$('.selector').bind('click', handler);
+5

, :

var getEventHandlers = function ($object, eventName) {
    var handlers = [],
        eventHandlers = $object.data("events")[eventName];
    if (eventHandlers && eventHandlers.length > 0) {
        for (var i = 0, l = eventHandlers.length; i < l; i++) {
            handlers.push(eventHandlers[i].handler);
        }
    }
    return handlers;
},
setEventHandlers = function ($object, eventName, handlers) {
    if (handlers && handlers.length > 0) {
        for (var i = 0, l = handlers.length; i < l; i++) {
            $object.bind(eventName, handlers[i]);
        }
    }
};
0

All Articles