2

Is there a way to guarantee that an event handler be the first responder?

For example let us say that we bind 2 event handlers to the same textarea

function first(event) {
    event.stopPropagation();
    console.log('first function');
}

function second(event) {
    console.log('second function');
}

$('body').on('keypress', 'textarea', first);
...
$('body').on('keypress', 'textarea', second);

Assuming that we have no control over the event handler order code declaration, is there a way for second to make it so that it is handled first?

developarvin
  • 4,940
  • 12
  • 54
  • 100
  • 1
    so we can say ***designing*** is for nothing. – King King Jun 04 '14 at 07:00
  • Take a look here: http://stackoverflow.com/questions/2360655/jquery-event-handlers-always-execute-in-order-they-were-bound-any-way-around-t – Irvin Dominin Jun 04 '14 at 07:11
  • You need to just physically write the code for the one you want executed before any others. Why is that so hard? – Ryan Jun 04 '14 at 07:16
  • @RPM The above are just examples. My actual use case is that these are in different modules/files. Some are 3rd party so I can't just simply "change the order". – developarvin Jun 04 '14 at 07:47
  • technically, the event handlers are pushed into some ***queue***, if you want to change the order of invoking, of course you have to have access to that ***queue***, sorting the elements in that queue in the order you want. You can even empty that queue and add new elements to that queue in the order you want again ... However I don't even know how to access to that queue, what type it is, ... If you sure about the existing elements in that queue (such as just `first` and `second` handlers), you can always remove all and add the handlers again in the order you want. – King King Jun 04 '14 at 08:35

2 Answers2

0

There is actually no way that you can actually control the order in which the event handlers are fired. They are designed to be fired in the order in which they were inserted and I dont think you can alter that. You can indeed make the event to fire at the top and bottom of the event chain, but it does not solve the problem always and in my opinion it gets messy too. A re look at the design is what I would suggest.

sdwaraki
  • 382
  • 1
  • 4
  • 12
0

If you use JQuery to bind your events, it guarantees that handlers are fired in the same order that they were bound.

Try both fiddle and check browser console:

Demo 1

Demo 2

But there are actually no way exist, by this you can control the order the event handlers are fired.

Please note that the W3C model does not state which event handler is fired first.

QuirksMode's Advanced event registration models

Your Question:

is there a way for second to make it so that it is handled first?

Check out this post

Community
  • 1
  • 1
Ishan Jain
  • 8,063
  • 9
  • 48
  • 75