This question came to my mind when I was experimenting with multiple events bound to the same object. Still I’m trying to find the most simple solution.
Imagine we have this markup:
<select class="class1 class2">
<option>Value 1</option>
<option>Value 2</option>
<option>Value 3</option>
</select>
<p></p>
And two methods bound to select for change event:
$(".class1").on("change", function() {
// first method for change
$("p").append("<div>Event for class1</div>");
});
$(".class2").on("change", function() {
// second method for change
$("p").append("<div>Event for class2</div>");
});
Now if you make selection change the content of p will be:
Event for class1
Event for class2
My ‘research’ question is how to rewrite the second on handler in order to make it fire its handler first. So finally the content of p should be:
Event for class2
Event for class1
The situation is so that we are unable to swap on statements in the source.
What ideas do you have?
There are solutions for this. One example is the
preBindby Jonathan Conway.This plugin manipulates jQuery’s event handler list for an element and adds an event at the front of it instead at the end.
So you use
$(...).preBindwhere you usedbindearlier. This does not apply to$(...).onbut similar solution could be easily made from this.This however is something I would strongly advise you not to do, as events competing for first place is often sign of bad architecture.