Once an event is bound in jQuery how do you get a reference to the event handler function?
If I attach a click event handler:
$(".selector").bind("click", function () {
// some handler function
});
How can I get a reference to that function? This doesn'开发者_如何学Got work:
var refToFunc = $(".selector").bind("click");
typeof refToFunc === "object"; // I want the function
I think bind("eventname")
in that case just returns the jQuery object and not the event handler function. It must be stored somewhere.
Very interesting question. You can retrieve it like this:
var refToFunc = $(".selector").data("events")["click"][0].handler;
Note that we used [0]
because you have an array of handlers, in case you bound more than one handler. For other events, just change to the event name.
EDIT In general, you could use the following plugin to get all handlers of the selected elements for an event (code not optimized yet):
$.fn.getEventHandlers = function(eventName){
var handlers = [];
this.each(function(){
$.each($(this).data("events")[eventName], function(i, elem){
handlers.push(elem.handler);
});
});
return handlers;
};
How to use it?:
$(".selector").getEventHandlers("click");
And it would return an array of functions containing all event handlers.
For your specific question, you could use this plugin like this:
var refToFunc = $(".selector").getEventHandlers("click")[0];
Hope this helps. cheers
Event handlers are kept in a data object, accessible through data
. For instance:
$('.selector').data('events').click[0].handler;
This gets the first event handler function bound to the click
event of this function.
If you want to keep a reference for the function e.g. for unbinding it, it would be better to store it in a variable or make it a named function.
var handler = function() {
// some content
});
$('.selector').bind('click', handler);
Here are the functions I ended up with:
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]);
}
}
};
精彩评论