I currently have a JavaScript component which triggers a DOM event using JQuery like so:
$(document).trigger('myevent', mydata);
Other components register an event handler and update themselves accordingly when receiving the event.
Now, I want to extend this functionality in such a way, that any of the registered components should have the chance to prevent those updates (i.e., reject the event).
I thought of having two events instead:
$(document).trigger('myevent-before', mydata);
if( ??? )
$(document).trigger('myevent', mydata);
Components which like to reject the update would register for the myevent-before
and return some kind of information in order to prevent the triggering side from triggering the actual myevent
.
Is this the way to go?
- If yes, how to formulate the if clause? Does
trigger()
return some indicator if any of the called event handlers returned false? - If no, what's the way to do such a thing in JavaScript?
Example 1:
- Main Component: Hey, does anyone have a problem with an upcoming update?
- Component A: No.
- Component B: No.
- Main Component: OK, then I'll trigger the actual update!
Example 2:
- Main Component: Hey, does anyone have a problem with an upcoming update?
- Component A: No.
- Component B: Yes.
- Main Component: Oh, ok, no update it is.
(note that there might be more than 2 components registered of course)