Backbone.js如何使集合只接受一类模型

时间:2014-10-09 22:02:09

标签: backbone.js

我是backbone.js的新手,我正在努力学习它。在下面的代码中,我希望我的名为“JokesCollection”的集合只接受添加“Joke”类的模型。我该怎么做到这一点?将“Collection”属性“model”设置为某个模型时,该集合是否应该只接受该模型类并确保同质性?不要缝。当我将“JokesCollection”类中的属性“model”分配给“Joke”时,它仍然接受添加类“Persson”的模型女巫不是我想要的。我只希望它接受添加“笑话”类的模型。

Joke = Backbone.Model.extend ({
    initialize: function(){
        console.log("Joke was created");
    },
    defaults: {
        joke : "",
        date : "0",
    }
});

JokesCollection = Backbone.Collection.extend({
    initialize: function(){
        console.log("JokesCollection was created");
    },
    model: Joke //  <=== Isn´t this supposed to ensure that the collection only accepts models of class "Joke"?
});

Person = Backbone.Model.extend ({
    initialize: function(){
        console.log("Person was created");
    },
    defaults: {
        username: "default",
        password: "default",
        email: "default"
    }
});



var person1 = new Person({username:"masterMind"});
var joke1 = new Joke({joke:"Girls are cute and funny hahahaha"});

jokesCollection = new JokesCollection();
jokesCollection.add(joke1);
jokesCollection.add(person1); // This adds a model of class "Person" to the collection. Witch is not what I want. It is not supposed to work! I want "jokesCollection" to only accept models of class "Joke".

console.log(jokesCollection.length); // length gets increased by 1 after adding "person1" to "jokesCollection". Again, it is no supposed to work from my point of view. I want "jokesCollection" to only accept models of class "Joke".
console.log(jokesCollection);

2 个答案:

答案 0 :(得分:1)

来自官方文档:

型号 collection.model

  

重写此属性以指定集合的​​模型类   包含的内容。如果已定义,则可以传递原始属性对象(和数组)   添加,创建和重置,属性将转换为   适当类型的模型。

看起来必须重写这样的add方法:

add: function(models, options) {

    var modelClass = this.model;
        isProperIns = this.models.every.(function(model){
            return model instanceof modelClass;
        });

    if (!isProperIns) {
        throw new Error("Some of models has unacceptable type")
    } 

    return this.set(models, _.extend({merge: false}, options, addOptions));
}

答案 1 :(得分:1)

Collection model属性的目的是来限制Collection可以接受的模型。相反,该属性定义Model类,Collection在需要创建新Model时将使用该类。例如,当您将Model属性的对象文字(而不是实例化的Model)传递给JokesCollection.add时,或者当您fetch模拟到{{1}时}},Backbone将使用JokesCollection作为Joke来实例化Model的新增内容。

有两种方法可以确保Collection仅填充JokesCollection个实例。第一种方法是永远不要直接向Joke添加Model个实例,而是:

A)通过JokesCollection

上的Joke调用来自服务器的新fetch

B)仅添加&#34; raw&#34; JokesCollection的{​​{1}}属性;不要添加实例化的Model

但是,如果您担心开发人员意外地向JokesCollection添加了非Model Joke,那么您的其他选择(由@Evgeniy首先建议)是覆盖Model Collection方法。与@ Evgeniy的答案不同,虽然我不建议重写Backbone的内部。相反,我会使用一个简单的覆盖,如果可能的话,只调用基本的Backbone方法:

JokesCollection