Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery - Make sure event handler is last to be executed in chain of handlers

Tags:

jquery

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?

like image 550
Kyle Avatar asked Jun 30 '10 15:06

Kyle


2 Answers

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

like image 90
David Radcliffe Avatar answered Sep 19 '22 18:09

David Radcliffe


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);
like image 41
Pedro Pinheiro Avatar answered Sep 22 '22 18:09

Pedro Pinheiro