I’m building a generic Backbone view for managing multiple child views. I sometimes need to perform logic to prepare these views before they are rendered. I’m considering using Backbone events to enable a pre_render hook, like this:
view = new (this.child_view);
this.trigger('pre_render', view);
view.render();
Will the events called by trigger() be performed synchronously, thus guaranteeing that they will all finish before the render() line is called?
Basically, yes, it’s synchronous.
Here’s the relevant section from the source:
The import function is
triggerEvents, which actually calls the handlers. According to the comments, it’s just an optimized dispatcher. Notice that they’re all calling.call()and.apply(), so the callback will complete before control is handed back to the caller.As others have mentioned, though, the trigger handlers are free to schedule their own callbacks if they are so inclined. Thus, whether or not the handlers will have finished their work before returning is dependent on the handler code itself.