I was looking for a way to allow two Backbone.Views to exchange information between them.
Here are some solutions to this problem:
1. The bad idea
We could just let them reference each other. Then view1 could say this.view2.doSomething() and it’s the easiest way to solve this.
However simple it may be, this will lead to a very tight coupling and a very bad design for our web app. If we have a circular dependency, we should probably rethink our design.
2. The good idea (that doesn’t always work)
We could have a model and share it to both views. One view will bind to an event on the model, and when the other view does something important, the model can trigger the event.
This is great except that a Backbone.View can only hold one Backbone.Model at a time. In many cases the two views will need to reference different models.
(Yes. I know that a View can hold extra models by ‘view.model2 = new Model()’ but this seems to stray from the convention)
Another weak point of this solution is that someone (probably the router, or a custom controller object) will have to create the model and hand it off to the two views. And if one of these views has subviews, we will have to pass it on to them and the chaos takes over.
3. The better idea
We could create a global notifications system where any object can bind to global events and any object can trigger a global event.
So instead of the first view registering for events triggered by the second view, it can register for global notifications.
This can be easily done by adding a Backbone.Notifications object:
Now we can let the first view bind to a global event (in this example: SomeViewRendered) and the second view can trigger it.
Seems to work, it’s easy and it creates a very decoupled interface between the different Backbone objects.
We can also use this to ask the Backbone.Router object to navigate somewhere else without direct calling it. Something like this:
A router can bind to this notification and act upon it. This allows any object to request anything from the system and if another object can provide it, it will magically happen.
Is this Neat or what? What do you think?