There are few ways to communicate between two backbone views and model.
Consider an application contains Menu view and you want to update the application area based on the menu selection.
For example, consider an e-commerce application which contains the following views.
1. MenuView
2. Recharge View
3. Shopping View
4. Book Ticket View
For this the very basic approach or the easiest way is that creating the object for all other three views in MenuView. But by doing this, all views are tightly coupled with one another.
To overcome this we’re going to use Event aggregator pattern.
Backbone provides Router concept for event aggregator.
In index.html we’ve included all the html templates.
index.html
After that, related Backbone view files are created with the basic information.
MenuView.js
var MenuView = Backbone.View.extend({ model : new MenuModel(), initialize : function(){ }, events : { }, render : function(){ var menuTemplate = _.template($('#menu-template').html()); this.$el.html(menuTemplate(this.model.toJSON())); return this; } });
RCView.js
var RCView = Backbone.View.extend({ el: '#contentArea', initialize : function(){ }, events : { 'click #rcSubmitButton':'doOnRCSubmitButton' }, render : function(){ var rcTemplate = _.template($('#recharge-template').html()); this.$el.html(rcTemplate(null)); return this; }, doOnRCSubmitButton : function(){ alert("RC click!!"); } });
As of now, views are containing only the render part which renders the corresponding template into the application area.
We’ve defined three links in the index.html menu area. For every menu item, there are independent actions. The event should be passed to corresponding views without any dependency. For this purpose we’ve created the router in the main.js file. Once the routes and its functions are defined, for all the menu selection it’ll redirected to its route.
main.js
$(document).ready(function(){ var menuView = new MenuView(); menuView.setElement($('#menuArea')); menuView.render(); new MyRouter(); Backbone.history.start(); }); var MyRouter = Backbone.Router.extend({ routes : { "recharge":"onRecharge", "bookticket" : "onBookTicket", "shop":"whileShopping" }, viewFactory : function(){ return{ rcView : typeof rcView == 'undefined' ? new RCView() : rcView, ticketView : typeof ticketView == 'undefined' ? new TicketView() : ticketView, shopView : typeof shopView == 'undefined' ? new ShopView() : shopView }; }, onRecharge : function(){ this.viewFactory().rcView.render(); }, onBookTicket : function(){ this.viewFactory().ticketView.render(); }, whileShopping : function(){ this.viewFactory().shopView.render(); } });
You can download this working sample in this Github URL.
Reference for event aggregator pattern : http://martinfowler.com/eaaDev/EventAggregator.html