我在一個集合中有兩種不同的模型,如何在視圖中訪問它們?這些問題有兩個部分,如果您不清楚問題,請告訴我們。如何訪問Collection中的多種類型的模型?
第1部分
模型1
Movie = Backbone.Model.extend({
initialize:function(){
console.log("The model 'Movie' initialized");
}
});
模型2
Songs = Backbone.Model.extend({
initialize:function(){
console.log("The model 'Songs' initialized");
}
});
這些模型創建的實例被添加到集合作爲陣列如下
var movie = new Movie({type:"movie",name:"Lord of the Rings",year:"2006"});
var songs = new Songs({type:"songs",name:"Rahna Thu", artist:"A R Rahman", album:"Delhi-6"});
var entertainment = new Backbone.Collection([movie,songs]);
現在,我如何在我的視圖內訪問這些模型?加載這些模型並綁定到模板?我不知道如果我是正確的,但我做了這樣的事情
MainView = Backbone.View.extend({
collection:entertainment,
initialize:function(){
$.each(this.collection.toJSON(),function(i,item){
if(item.type=="songs"){
alert("Song: "+item.name+" Artist: "+item.artist+" Album: "+item.album);
}
});
}
});
var mainview = new MainView({el:$('body')});
雖然我得到正確的警覺,我需要知道,如果這是這樣做的正確方法。
第二部分
現在我的問題的第二部分。如果這些模型只有'urlRoot'呢?我如何預取模型並填充集合?
I.e.在我的第二個場景我的型號如下
Movie = Backbone.Model.extend({
urlRoot:"https://localhost:8080/entertainment/movies"
});
和
Songs = Backbone.Model.extend({
urlRoot:"https://localhost:8080/entertainment/songs"
});
現在,我怎麼這些模型添加到收集和訪問他們的觀點裏面?
我期待的實際解決方案是在加載儀表板頁面時加載多個數據,例如網格,圖表和其他服務器端數據。由於所有這些都需要在頁面加載時填充,所以我想到了像這樣的解決方案。我在這裏做正確的事情?還是有更好的方法來做到這一點?
對不起,這個問題很長,但真的很感謝這裏的一些專家建議。