2012-10-19 197 views
0

我想建立一個集合,但需要動態構建它,因爲我不知道要推多少。目前我所做的是;骨幹集合推環

var DataCollection = Backbone.Collection.extend({ 
      model : dataModel 
     }); 

     var dataModel = Backbone.Model.extend({ 
      defaults : { 
       dataID : 'unknown', 
       text : 'unknown', 

      } 
     }); 


     var linkPrev = new dataModel({ dataID: "Prev", text: "Prev" }); 
     var link1 = new dataModel({ dataID: "1", text: "1" }); 
     var link2 = new dataModel({ dataID: "2", text: "2" }); 
     var link3 = new dataModel({ dataID: "3", text: "3" }); 
     var linkNext = new dataModel({ dataID: "Next", text: "Next" }); 

     var myDataCollection = new DataCollection(); 
     //myDataCollection.push(linkPrev); 
     myDataCollection.push(link1); 
     myDataCollection.push(link2); 
     myDataCollection.push(link3); 
     myDataCollection.push(linkNext); 

不用手動說

link1 = new dataModel({ dataID: "1", text: "1" }); 
myDataCollection.push(link1); 

我可以創建列表中刪除此動態..

舉例來說,如果我有4個環節,我想與數據ID添加LINK4:4 ,TextID:4 ... etc ...

回答

2

如果您需要在初始化時填充集合,您可以簡單地傳遞一個對象數組來填充,不需要爲每個對象創建一個模型,Backbon e.Collection會爲你做:

var DataCollection = Backbone.Collection.extend({ 
    model : DataModel 
}); 

var DataModel = Backbone.Model.extend({ 
    defaults : { 
     dataID : 'unknown', 
     text : 'unknown' 
    } 
}); 

var myDataCollection = new DataCollection([ 
    { dataID: "Prev", text: "Prev" }, 
    { dataID: "1", text: "1" }, 
    { dataID: "2", text: "2" }, 
    { dataID: "3", text: "3" }, 
    { dataID: "Next", text: "Next" } 
]); 
+0

謝謝...... – myTD