There are places in my application where an object should emit an event and should delay execution untill all event handlers have completed work. The event handlers might be performing an asynchronous operation (e.g. writing to database).
Application.on("login", function(evt) {
// Asynchronous operation (e.g. update info in database)
});
Application.trigger("login").then(function() {
// Execute stuff after all (async) event handlers are done
});
I've looked around and haven't found any established design patterns for this. I've got an implementation I'm happy with, but I'm curious if anyone has solved this differently?
My solution is to add a
promises[]
property to theevt
argument. Asynchronous event callbacks simply add a promise to this array and thetriggerAsync
function returns a promise that wait on all the promises to settle.http://jsfiddle.net/nonplus/9aCC4/
Implementation of the triggerAsync method (using Backbone events and jQuery promises, but should work for other stacks, too):
Usage of triggerAsync:
Implementation of an async event handler: