Backbone.js:“backbone . collection”;类支持不同类型的对象,以及类如何工作

Backbone.js: The "Backbone.Collection" class supporting objects of different types, and how the class works

本文关键字:对象 何工作 工作 同类型 backbone js collection 支持 Backbone      更新时间:2023-09-26

通过阅读Addy Osmani编写的名为"开发Backbone.js应用程序"的教科书并在其上尝试了一个实际示例,我可以看到Backbone的所有元素。集合类可以有不同类型的元素。扩展主干的类。集合也可以保存不同类型的元素,就像所有的元素不必是一致的。

让我给你展示一下我在我的例子中使用的代码:

var ToDosCollection = new Backbone.Collection();
ToDosCollection.add([
    { title: 'go to Jamaica.', completed: false },
    { task: "aldvjalkdgj", level: 3, timeDue: "6:00 PM Today" }
]);
console.log('Collection size: ' + ToDosCollection.length);
ToDosCollection.reset([
    { slogan: "Curse you, Sephiroth.", population: 5500,},
    { project: "Final Fantasy X" },
    { amount: 500 }
]);
// Above logs 'Collection reset.'
console.log('Collection size: ' + ToDosCollection.length);
alert(JSON.stringify(ToDosCollection.get(0)));
var GitHubRepository = Backbone.Model.extend({
        defaults: {
        nameOfRepository : "",
        owner : "",
        members : [],
        dateCreated : "",
        commits: 0,
        additions: 0,
        deletions: 0,
    },
    initialize : function(){
        this.on("change", function() {
        console.log("CHANGE DETECTED");
    });
    this.on("change:nameOfRepository", function(){
        console.log("The name of the repository has been changed.");
    });
    this.on("change:owner", function(){
        console.log("The owner of the repository has been changed.");
    });
    this.on("change:members", function(){
        console.log("The members this repository belongs to have been changed.");
    });
    this.on("change:dateCreated", function(){
        console.log("The date this repository was created has been changed.");
    });
    this.on("change:commits", function(){
        console.log("The # of commits this repository has have been changed.");
    });
    this.on("change:additions", function(){
        console.log("The # of additions this repository has have been changed.");
    });
    this.on("change:deletions", function(){
        console.log("The # of deletions this repository has have been changed.");
        });
    }
});
var GitHubRepositoryCollection = Backbone.Collection.extend({
    model: GitHubRepository
});
var newCollection = new GitHubRepositoryCollection();
newCollection.add(
    {newObject: new GitHubRepository()},
    {title: "Rabbits"},
    {elementNumber: 5}
);

我理解对了吗?或者说,这到底是怎么回事?对我来说,我觉得我在做一个类似于Java中支持Object对象的ArrayList的实例。

编辑:考虑到我在这个问题上至少得到了一个反对票,我想问,"ItemView在Backbone.js中是如何工作的?"

为了在集合中呈现每个模型的itemview,我想最好保持每个模型类似。否则,你将不得不为每个模型不同地构建itemview,这将增加你编写代码的开销,这是不好的,因为我们应该使用骨干来渲染视图,这些视图将以相同的方式呈现相同的数据。如果你想呈现不同的itemview,最好有不同的组合视图或集合视图,这将自动完成你的任务,最终将减少你的开销。