Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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't 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.

like image 575
travis Avatar asked Jul 08 '11 23:07

travis


2 Answers

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

like image 93
Edgar Villegas Alvarado Avatar answered Sep 22 '22 01:09

Edgar Villegas Alvarado


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);
like image 35
lonesomeday Avatar answered Sep 20 '22 01:09

lonesomeday