2013-04-24 70 views
0

現在我明白這可以通過引用來自其模型的視圖來實現。然而,我試圖堅持Backbone.js的「最佳實踐」,在那裏被認爲是糟糕的做法 - 模型 - >視圖往往是一對多的關係。Backbone.js從集合中獲得以前的視圖

我的問題是這樣的(代碼樣本,以幫助您直觀的問題):

我的分組視圖的陣列。每個視圖的分組數組都包含來自多個集合的視圖。例如,

var views; // Assume views is pre-populated with an array of views, each view's model may be stored in a different collection. 

var viewGroups = _.groupBy(views, function(view) { 
    return view.model.attributes.timestamp; // Unix timestamp for example 
}); 

當我通過我需要訪問直接來自每個視圖的模型前,在它的收藏模型的觀點分組視圖循環。

我能夠訪問以前的模型集合中,像這樣:

_.each(viewGroups, function(viewGroup) { 
    _.each(viewGroup, function (view) { 
     var model = view.model; 
     var collection = model.collection; 
     var previousModel = collection.at(collection.indexOf(model) - 1); 
    }); 
}); 

但因爲沒有從模型隸屬關係,它的意見,我無法找出哪些視圖訂閱以前的型號在集合中。

var previousModelsViews = ???

我將如何做到這一點之後的設計模式,模型是無知的觀點。

+0

你真的需要訪問的看法,或者你想要的視圖來執行的東西? – Loamhoof 2013-04-24 11:23:49

+0

@Loamhoof我需要訪問視圖,因爲我需要執行DOM操作。 – 2013-04-24 11:54:21

+1

然後我想你可以在之前的模型中觸發一個自定義事件,並讓視圖做他們的東西。 – Loamhoof 2013-04-24 12:02:46

回答

1

您不需要知道該視圖。只需在意見添加自定義事件偵聽器:

查看:

initialize : function(){ 
    this.model.on('customAction', this.customAction); 
}, 
customAction : function(){ 
    //here you could do the DOM manipulation that you need on your previous view 
} 

並在您的代碼添加此:

var previousModel = collection.at(collection.indexOf(model) - 1); 
previousModel.trigger('customAction'); 

更新:你以後再更新您的要求: 我仍然認爲一切都可能與事件有關,只是在以前的觀點發出其他事件:

查看:

initialize : function(){ 
    this.model.on('customAction', this.customAction); 
    this.model.on('PreviousWindowSize', this.previousSizeReceived); 
}, 
//Previews View will arrive here 
customAction : function(nextModel){ 
    nextModel.trigger('PreviousWindowSize', {width: this.$el.width()}); 
}, 
//Current View will receive the size of the previous View here 
previousSizeReceived : function(size){ 
    console.log(size); 
} 

並在您的代碼添加這個(檢查我加在觸發以前的型號):

var previousModel = collection.at(collection.indexOf(model) - 1); 
previousModel.trigger('customAction', previousModel); 
+0

謝謝,但我應該更好地解釋,我需要獲取前一個視圖元素的高度和位置(這就是爲什麼我需要訪問視圖)供當前視圖元素使用(爲什麼觸發事件將不起作用) 。 – 2013-04-25 09:43:29

+0

我更新了我的答案,因爲你更新了你的問題。我添加了一些可以使用的邏輯,請讓我知道其他任何疑問 – 2013-04-25 10:16:23

+0

感謝您的答案,但最終我決定將此邏輯從Backbone模型/視圖邏輯中移除,因爲我意識到了更快的方法這樣做。 – 2013-04-26 09:15:43