I'm looking for a way to achieve the following. I could build some mechanism to do this, I'm asking for something built-in or a really simple way, if it exists and I'm missing it.
Edit: Please note that I'm talking about events in random objects, not in DOM elements. The events order cannot be managed using the parent, etc. as suggested in the possible duplicate.
Edit 2: Maybe an after-all-handlers-have-been-called callback? Or an always-last-to-be-executed handler?
Given:
var someObject={};
$(someObject).on("event",function() { console.log('Default handler'); });
...
$(someObject).on("event",function() { console.log('Other handler'); });
When doing:
$(someObject).triggerHandler("event");
The output is:
Default handler
Other handler
We all know this. The problem is: What if I would want to make the first event the "default" handler, to be executed if there aren't other event handlers (not a problem there) or if the other handlers didn't stop the event propagation (here is the problem).
I'm looking for a way to be able to do something like:
$(someObject).on("event",function(ev) { ev.preventDefault(); });
and prevent the first event handler from executing. In this example is not working given the execution order. Reversing the execution order is not the correct way to do it.
TL;DR
Is it possible to set a default handler, one to be called in case there's no other handlers and the event hasn't been canceled?
Edit 3: To give you a better idea, the current approach is the following (names are made up for this example):
var eventCanceled=false;
function doTheEvent() {
$(someObject).triggerHandler("event");
if(!eventCanceled) defaultEventHandler();
}
//To be called inside the handlers to stop the default handler
function cancelTheEvent() {
eventCanceled=true;
}
I just want to get rid of this and be able to use triggerHandler
directly.