Using an event dispatcher
Notice one thing in the previous scenario: to listen to the loggedin
event, all the other components of the application should have a reference to that loginView
. Is this really required? It may seem to a few components that keeping a reference to loginView
is irrelevant, but they have to do so because they need to listen to the loggedin
event on this loginView
object. Dependency injection in such a way can be painful even when you are developing a simple application. Sometimes we may need a common object that will play the role of a central event manager and can be used throughout the application to trigger and listen to events. The simplest event dispatcher can be defined in the following way:
var vent = _.extend({}, Backbone.Events); // Listen to a custom event vent.on('customevent', function(){ console.log('Custom event fired'); }); // Fire the event vent.trigger('customevent');
When we make the vent
variable available at the application-level, it can work...