Calling the view function from another view - reference

My application has the following views. Basically I want to call show_house () in App.MapView when the app.HouseListElemView application li is clicked.

What would be the best way to do this?

App.HouseListElemView = Backbone.View.extend({ tagName: 'li', events: { 'click': function() { // call show_house in App.MapView } }, initialize: function() { this.template = _.template($('#house-list-template').html()); this.render(); }, render: function() { var html = this.template({model: this.model.toJSON()}); $(this.el).append(html); }, }); App.MapView = Backbone.View.extend({ el: '.map', events: { 'list_house_click': 'show_house', }, initialize: function() { this.map = new GMaps({ div: this.el, lat: -12.043333, lng: -77.028333, }); App.houseCollection.bind('reset', this.populate_markers, this); }, populate_markers: function(collection) { _.each(collection.models, function(house) { var html = 'hello' this.map.addMarker({ lat: house.attributes.lat, lng: house.attributes.lng, infoWindow: { content: html, } }); }, this); }, show_house: function() { console.log('show house'); } }); 
+8
source share
1 answer

The current home is indeed part of the global state of the application, so create a new model to store your global state of the application:

 var AppState = Backbone.Model.extend({ /* maybe something in here, maybe not */ }); var app_state = new AppState; 

Then your HouseListElemView can respond to clicks by setting the value to app_state :

 App.HouseListElemView = Backbone.View.extend({ //... events: { 'click': 'set_current_house' }, set_current_house: function() { // Presumably this view has a model that is the house in question... app_state.set('current_house', this.model.id); }, //... }); 

and then your MapView just listens for 'change:current_house' events from app_state :

 App.MapView = Backbone.View.extend({ //... initialize: function() { _.bindAll(this, 'show_house'); app_state.on('change:current_house', this.show_house); }, show_house: function(m) { // 'm' is actually 'app_state' here so... console.log('Current house is now ', m.get('current_house')); }, //... }); 

Demo: http://jsfiddle.net/ambiguous/sXFLC/1/

You might want current_house be a real model, not just an id , but it's easy.

You can probably find all sorts of other uses for app_state after it appears. You can even add a bit of REST and AJAX and get consistency for the settings of your application to a large extent for free.

Events are the usual solution to every problem in Backbone, and you can create models for anything, you can even make temporary models strictly for gluing things together.

+14
source share

All Articles