骨幹應該適用於這種情況。
創建一箇中心事件輪詢器。這從服務器上獲取所有類型的事件,並將它們發佈到應用程序(未測試)的其餘部分:
var EventPoller = Backbone.model.extend({
url: "events/",
poll: function(){
this.fetch({
success: function(self, response){
self.handleEvents(response);
self.poll();
}, error: function(self){
self.poll();
}
})
},
handleEvents: function(events){
var self = this;
$(events).each(function(index, event){
self.trigger(event.name, event.data);
});
}
});
然後讓幾個模型偵聽這些事件:
var StockModel = Backbone.Model.extend({
initialize : function() {
this.poller.bind('stockChange', this.changeStock, this);
},
changeStock: function(stock){
this.set({name: event.name});
}
});
終於讓視圖監聽模型的變化:
var StockView = Backbone.View.extend({
initialize : function() {
this.model.bind('change:name', this.updateStock, this);
//this.poller.bind('stockChange', this.updateStock, this); //you could also listen for poll events directly in view with out having a model for each view.
},
updateStock: function(){
$(this.el).html(model.get("name"));
}
});
要設置輪詢和觀點:
var eventPoller = new EventPoller();
var stockModel = new StockModel({poller: eventPoller})
var stockView = new StockView({model:stockModel});
eventPoller.poll();
一般性建議是骨幹需要花費一些時間來學習,但如果您閱讀文檔並遵循一些基本示例,則您將加快步伐。
也許最主要的困惑是this
。我會建議使用螢火蟲和調試通過應用程序,看看如何this
更改。