2012-06-14 20 views
8

我的應用程序中有以下視圖。基本上我想在App.HouseListElemView的li被點擊時調用App.MapView中的show_house()。從另一個視圖調用查看功能 - Backbone

這樣做的最好方法是什麼?

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'); 
    } 
}); 

回答

14

當前房子真的是你的應用程序的全局狀態的一部分,以便創建一個新的模式來保存您的全局應用程序狀態:在app_state設置一個值

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

然後你HouseListElemView可以響應點擊:

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); 
    }, 
    //... 
}); 

,然後你只需MapView偵聽來自事件:

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')); 
    }, 
    //... 
}); 

演示:http://jsfiddle.net/ambiguous/sXFLC/1/

你可能想current_house是一個實際的模式,而不是當然簡單的id但是這很容易。

一旦你有了它,你可能會找到各種其他用途app_state。您甚至可以添加一點REST和AJAX,並且可以免費獲得應用程序設置的持久性。

事件是Backbone中每個問題的常見解決方案,您可以爲任何需要的模型創建模型,甚至可以將臨時模型嚴格地粘合在一起。

+0

美麗..謝謝 – AlexBrand

+0

+1。請原諒我的無知,但這種方法/ appstate和擴展[Backbone.Events]之間的區別是什麼(http://lostechies.com/derickbailey/2012/04/03/revisiting-the-backbone-event-aggregator-lessons-瞭解/)傳統的PubSub? – TYRONEMICHAEL

+1

@TyroneMichael:大部分容易持久。 PubSub只是路由信息並忘記它,模型會記住它,並且可以很容易地將狀態保存到服務器。 –