How to Order Events Bound with Jquery

How to order events bound with jQuery

I had been trying for ages to generalize this kind of process, but in my case I was only concerned with the order of first event listener in the chain.

If it's of any use, here is my jQuery plugin that binds an event listener that is always triggered before any others:

** UPDATED inline with jQuery changes (thanks Toskan) **

(function($) {
$.fn.bindFirst = function(/*String*/ eventType, /*[Object])*/ eventData, /*Function*/ handler) {
var indexOfDot = eventType.indexOf(".");
var eventNameSpace = indexOfDot > 0 ? eventType.substring(indexOfDot) : "";

eventType = indexOfDot > 0 ? eventType.substring(0, indexOfDot) : eventType;
handler = handler == undefined ? eventData : handler;
eventData = typeof eventData == "function" ? {} : eventData;

return this.each(function() {
var $this = $(this);
var currentAttrListener = this["on" + eventType];

if (currentAttrListener) {
$this.bind(eventType, function(e) {
return currentAttrListener(e.originalEvent);
});

this["on" + eventType] = null;
}

$this.bind(eventType + eventNameSpace, eventData, handler);

var allEvents = $this.data("events") || $._data($this[0], "events");
var typeEvents = allEvents[eventType];
var newEvent = typeEvents.pop();
typeEvents.unshift(newEvent);
});
};
})(jQuery);

Things to note:

  • This hasn't been fully tested.
  • It relies on the internals of the jQuery framework not changing (only tested with 1.5.2).
  • It will not necessarily get triggered before event listeners that are bound in any way other than as an attribute of the source element or using jQuery bind() and other associated functions.

Can I find events bound on an element with jQuery?

In modern versions of jQuery, you would use the $._data method to find any events attached by jQuery to the element in question. Note, this is an internal-use only method:

// Bind up a couple of event handlers
$("#foo").on({
click: function(){ alert("Hello") },
mouseout: function(){ alert("World") }
});

// Lookup events for this particular Element
$._data( $("#foo")[0], "events" );

The result from $._data will be an object that contains both of the events we set (pictured below with the mouseout property expanded):

Console output for $._

Then in Chrome, you may right click the handler function and click "view function definition" to show you the exact spot where it is defined in your code.

jQuery event handlers always execute in order they were bound - any way around this?

Updated Answer

jQuery changed the location of where events are stored in 1.8. Now you know why it is such a bad idea to mess around with internal APIs :)

The new internal API to access to events for a DOM object is available through the global jQuery object, and not tied to each instance, and it takes a DOM element as the first parameter, and a key ("events" for us) as the second parameter.

jQuery._data(<DOM element>, "events");

So here's the modified code for jQuery 1.8.

// [name] is the name of the event "click", "mouseover", .. 
// same as you'd pass it to bind()
// [fn] is the handler function
$.fn.bindFirst = function(name, fn) {
// bind as you normally would
// don't want to miss out on any jQuery magic
this.on(name, fn);

// Thanks to a comment by @Martin, adding support for
// namespaced events too.
this.each(function() {
var handlers = $._data(this, 'events')[name.split('.')[0]];
// take out the handler we just inserted from the end
var handler = handlers.pop();
// move it at the beginning
handlers.splice(0, 0, handler);
});
};

And here's a playground.


Original Answer

As @Sean has discovered, jQuery exposes all event handlers through an element's data interface. Specifically element.data('events'). Using this you could always write a simple plugin whereby you could insert any event handler at a specific position.

Here's a simple plugin that does just that to insert a handler at the beginning of the list. You can easily extend this to insert an item at any given position. It's just array manipulation. But since I haven't seen jQuery's source and don't want to miss out on any jQuery magic from happening, I normally add the handler using bind first, and then reshuffle the array.

// [name] is the name of the event "click", "mouseover", .. 
// same as you'd pass it to bind()
// [fn] is the handler function
$.fn.bindFirst = function(name, fn) {
// bind as you normally would
// don't want to miss out on any jQuery magic
this.bind(name, fn);

// Thanks to a comment by @Martin, adding support for
// namespaced events too.
var handlers = this.data('events')[name.split('.')[0]];
// take out the handler we just inserted from the end
var handler = handlers.pop();
// move it at the beginning
handlers.splice(0, 0, handler);
};

So for example, for this markup it would work as (example here):

<div id="me">..</div>

$("#me").click(function() { alert("1"); });
$("#me").click(function() { alert("2"); });
$("#me").bindFirst('click', function() { alert("3"); });

$("#me").click(); // alerts - 3, then 1, then 2

However, since .data('events') is not part of their public API as far as I know, an update to jQuery could break your code if the underlying representation of attached events changes from an array to something else, for example.

Disclaimer: Since anything is possible :), here's your solution, but I would still err on the side of refactoring your existing code, as just trying to remember the order in which these items were attached can soon get out of hand as you keep adding more and more of these ordered events.

Get all the events bound by .on() in jQuery

Since you bound your events to document element, try this:

$(document).data("events")

Is it possible to obtain a list of events bound to an element in jQuery?

Every event is added to an array.

This array can be accessed using the jQuery data method:

$("#element").data('events')

To log all events of one object to fireBug just type:

console.log ( $("#element").data('events') )

And you will get a list of all bound events.


Update:

For jQuery 1.8 and higher you have to look into the internal jQuery data object:

$("#element").each(function(){console.log($._data(this).events);});
// or
console.log($._data($("#element")[0]).events);

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

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

what events are bound?

If you are using Safari or Chrome, you can open up the Developer Tools and inspect the element (by clicking the magnifying glass). In the Event Listeners tab on the right it will tell you the binded events to that element, with their functions and locations.

OR to do this via code:

$('selector').data('events'); // get
console.dir($('selector').data('events')); // display in firefox firebug or webkit's developer tools

Order of execution of jquery event handlers in respect to (inline) javascript event handlers

I'm not sure about the specs but I presume that event handlers are just queued in the same order as you define them. Inline handlers are defined right in the DOM node so nothing else can go earlier.

The most elegant way is to write all your JavaScript in an unobtrusive way, i.e., keep it separated from HTML (you appear to be mixing programming styles). Whatever, you can intercept form submission by attaching an onsubmit handler to the form:

$("form").submit(function(){
// Do stuff
return true;
});

Update

I've done some testing and it appears that an onsubmit handler attached to a form via jQuery does not get triggered when you call the DOM's submit() method somewhere else. Here's a workaround:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head><title></title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript"><!--
jQuery(function($){
$("a").each(function(i, a){
a.onclick = function(){ // Remove previous handlers
alert("I will no longer submit the form");
$(this).closest("form").submit();
};
});
$("form").submit(function(){
alert("I'll take care myself, thank you");
$("input[name=foo]").val("Another value");
return true;
});
});
//--></script>
</head>
<body>

<form action="" method="get">
<input type="text" name="foo" value="Default value">
<a href="javascript:;" onclick="document.forms[0].submit()">Submit form</a>
</form>

</body>
</html>


Related Topics



Leave a reply



Submit