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 个链接,我希望在 link4 中添加 dataID: 4, TextID: 4... 等等...

4

1 回答 1

2

如果您需要在初始化时填充集合,您可以简单地传递一个对象数组来填充,无需为每个对象创建模型,Backbone.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" }
]);
于 2012-10-19T08:13:22.860 回答