In Backbone, you can create your own EventAggregator
and bind it to your app-object:
MyApp = {};
MyApp.vent = _.extend({}, Backbone.Events);
Derick Bailey, the author of Marionette, made such EventAggregator an attribute of each marionette Application, available through .vent
(read more here):
MyApp = new Backbone.Marionette.Application();
MyApp.vent.on("some:event", function(){
alert("some event was fired!");
});
MyApp.vent.trigger("some:event");
The event aggregator is some kind of a singleton. That's fine, one broker per application is enough. But I don't find attaching this broker to application object handy, because it's not comfortable for other objects in the system to communicate with it. Many apps rely on RequireJS, when you create a view or a model, you have to pass the application-singleton reference to it, to enable listening on events published by this broker. And my question is - why isn't the default aggregator available as a direct singleton via requirejs, e.g.
define([], function() {
var Vent = _.extend({}, Backbone.Events);
var myVent = new Vent();
return myVent;
})
Then we could just require this in any requirejs-module of the project and have the same instance without the need to manually pass the vent as a constructor parameter (e.g.var model = new MyModel({vent: vent});
). Or another approach, maybe even better - why doesn't Marionette inject a reference to the application's event aggregator to all created models and views, so that we don't have to care about that?
Summing up, the question is: why is it recommended to make the event aggregator an attribute of application object, since it forces us to manually pass the reference to it to every single object it will need to communicate with?
By the way, Jeremy and Derick are very welcome to answer this question. I guess this design makes sense, but I can't see it yet.