Is there a way to make sure the event handler you attach is the last in the chain of event handlers to be executed?
I have an event handler that submits a form by ajax, but at a later time, after I attach my ajax submitting handler, another handler is attached to the form to do validation logic. The validation logic should occur before the ajax submitting handler, but it doesn't since it was bound afterwards.
Is there a way to make it so my ajax submitting handler always is the last handler in the chain of handlers to be executed, without changing the order in which the handlers are bound?
I don't think there is a way to manipulate the order directly.
Take a look at this: How to order events bound with jQuery
My solution (http://jsfiddle.net/968jj/1345/) :
$.fn.lastHandler = function (events, handler) {
var element = $(this);
events = events.split(' ');
for (var evt in events) {
var event = $(element).data("events")[events[evt]];
var hsucess = null;
$.each(event, function (i, h) {
if (h.handler == handler) {
hsucess = h;
}
});
var index = event.indexOf(hsucess);
if (index > -1) {
event.splice(index, 1);
event.push(hsucess);
}
}
}
usage:
$(function() {
var m1 = function(){ alert("mouseover to be the last"); };
var m2 = function(){ alert("mouseover to be the first"); };
var m3 = function(){ alert("mouseover to be the second"); };
$("#el").mouseover(m1);
$("#el").mouseover(m2);
$("#el").mouseover(m3);
$("#el").lastHandler('mouseover',m1);
});
With some HTML
<div id="el"></div>
and some CSS
div { width: 200px; height: 200px; background-color: red; }
You can use it with any one or more than one event:
$("#el").lastHandler('keypress keyup change',fnHandler);
$("#el").lastHandler('click mouseover',fnHandler);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With