具有多个不同模型类别的Feed主干集合 [英] Feed backbone collection with multiple different model classes

查看:150
本文介绍了具有多个不同模型类别的Feed主干集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have several models which have their own url/api they can fetch.

我想将它们保存在一个集合中.

I would like to keep them in a collection.

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

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

Let me know what you think, if you have any theoretical reading/advise.

推荐答案

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

A collection can contain any raw objects or any models derived from a Backbone.Model. Fetching a collection makes sense only if you have an API endpoint which returns an array of objects.

如果您要获取特定模型,则可以保留对其的引用,或者只是 get 放入收藏夹中,然后在其上调用fetch.

If you want to fetch a specific model, you can keep a reference to it, or just get it inside your collection, and then call fetch on it.

当您发生id冲突时,可能会导致问题,在这些冲突中,相同的ID被视为相同的模型,并且会合并在一起.

It can cause problems when you have id collisions, where identical ids are considered the same model and are merged together.

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 .
  • 使用 GUID .
  • 创建一个由标识数据组成的自定义id属性,例如在type属性之前添加. (book1note1).
  • don't use ids for these models if possible, Backbone will use their cid.
  • use GUIDs.
  • make a custom id attribute composed of identifying data, like prepending the type attribute. (book1, note1).

制作多模型集合的一种方法是使用 model属性作为功能.尽管默认情况下它不能防止id冲突.

A way to make a multi model collection is to use the model property as a function. Though it doesn't prevent id collision by default.

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'
}]);

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

See similar questions about multiple models in a collection:

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

这篇关于具有多个不同模型类别的Feed主干集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆