Question

I've been reading Backbone Fundamentals and have been planning on using the mediator and facade patterns in a new project, however on reading I was wondering why it wouldn't be possible to just use the apps main router object, or any object which extends Backbone.Events as the mediator, rather than implementing the subscribe and publish methods as outlined in the book.

Now that Backbone 0.9.9's docs explicitly mention using the Backbone object (which now extends from Backbone.Events) as a global event bus, I'm even more curious about this. Could anyone clarify if this is a good option, and if not why?

Was it helpful?

Solution

I don't see any problems with using the Backbone root object as a mediator. It wouldn't necessarily be a great idea to use you application's main router as the event bus, because that would require the router instance to be accessible globally to every part of the application. Using the Backbone root object largely avoids this pitfall, because it is already a global singleton instance.

If one wanted to really look for reasons not to use Backbone as the mediator, you could argue that doing so would couple all the publishers and subscribers to Backbone, and thus reduce the portability of the consumer code. In addition you lose control over the interface you expose. In an AMD/Module pattern this would mean that you would have to import Backbone to modules which have no business accessing the Backbone root object.

I don't see this as an issue, because your application is most likely fully dependent on Backbone as it is. But if you are feeling paranoid, you can use the Backbone.Events implementation without exposing the global object:

//mediator.js
define(['backbone', 'underscore'], function(Backbone, _) {
    return _.extend({}, Backbone.Events);
});

In which case the consumers are only taking a dependency on the interface, not the implementation, and could change the implementation details of the mediator mediator simply by implementing the on, off and trigger methods yourself.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top