【问题标题】:Feed backbone collection with multiple different model classes具有多个不同模型类的 Feed 主干集合
【发布时间】:2016-11-17 04:58:42
【问题描述】:

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

我想把它们收藏起来。

  • 听起来是个好主意吗?
  • 您将如何获取它们? (我只是想从集合中获取我想要更新的模型然后获取它)

如果您有任何理论阅读/建议,请告诉我您的想法。

【问题讨论】:

标签: javascript backbone.js backbone.js-collections


【解决方案1】:

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

如果您想获取特定模型,您可以保留对它的引用,或者将 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'
}]);

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

【讨论】:

    猜你喜欢
    • 2012-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-30
    相关资源
    最近更新 更多