我是backbone.js的新手,我正在試着學習它。在下面的代碼中,我希望我的集合名爲「JokesCollection」,只接受類「Joke」的添加模型。我該如何做到這一點?將「收集」屬性「模型」設置爲某個模型時,是不是隻接受該模型類並確保同質性的集合?不要這樣縫。當我將「JokesCollection」類中的屬性「model」分配給「Joke」時,它仍然接受增加「Persson」類的模型,這不是我想要的。我只希望它接受添加類「笑話」的模型。Backbone.js如何讓收藏只接受一類模型
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);
如果您發現該答案有用,請將其標記爲正確 – Evgeniy 2014-11-24 10:44:34