Feed backbone collection 具有多个不同的模型 类

Feed backbone collection with multiple different model classes

我有几个模型,它们有自己的 url/api 它们可以获取。

我想将它们保存在 collection 中。

让我知道你的想法,如果你有任何理论 reading/advise。

集合可以包含任何原始对象或从 Backbone.Model 派生的任何模型。仅当您有一个 API 端点且 returns 一个对象数组时,获取集合才有意义。

如果您想获取特定模型,您可以保留对它的引用,或者只是 get 它在您的集合中,然后对其调用 fetch

当你有 id 冲突时,它可能会导致问题,其中相同的 ID 被认为是相同的模型并合并在一起。

var book = new Book({ id: 1, title: "My Book" }),
    note = new Note({ id: 1, title: "note test" });

var collection = new Backbone.Collection([book, note]);
console.log(collection.length); // 1

避免id 碰撞的方法:

  • 如果可能,不要为这些模型使用 ID,Backbone 将使用它们的 cid
  • 使用GUIDs.
  • 制作一个由识别数据组成的自定义 id 属性,例如在 type 属性前添加。 (book1, note1).

制作多模型集合的一种方法是将 model property 用作函数。虽然默认情况下它不会阻止 id 碰撞。

var BooksAndNotes = Backbone.Collection.extend({

    /**
     * Different models based on the 'type' attribute.
     * @param {Object} attrs   currently added model data
     * @param {Object} options
     * @param {Backbone.Model} subclass dependant of the 'type' attribute.
     */
    model: function ModelFactory(attrs, options) {
        switch (attrs.type) {
            case "book":
                return new Book(attrs, options);
            case "note":
                return new MTextSession(attrs, options);
            default:
                return new Backbone.Model(attrs, options);
        }
    },
    // fixes this.model.prototype.idAttribute and avoids duplicates
    modelId: function(attrs) {
        return attrs.id;
    },
});

var collection = new BooksAndNotes([{
    title: "My Book",
    type: 'book'
}, {
    title: "note test",
    type: 'note'
}]);

查看关于集合中多个模型的类似问题:

  • A Backbone.js Collection of multiple Model subclasses
  • Backbone Collection with multiple models?