具有特定类型的 Backbone.Js 集合 [英] Backbone.Js Collection with Specific Types
问题描述
我有一个叫做 History 的 BackboneJS 集合,它可以包含几个 Backbone JS 模型之一(从 HistoryItem 扩展到 Backbone.Model),我试图找到一种在加载时重新创建它的方法,不幸的是它似乎是 BackboneJS 集合只能在特定型号指定,例如
I have a BackboneJS collection called History which can contain one of several Backbone JS models (which extend from HistoryItem which extends from Backbone.Model), I trying to find a way to have this recreated when loading, unfortunately it seems BackboneJS collection can only specify at particular model e.g.
HistoryCollection = Backbone.Model.extend({
model: app.models.HistoryItem
})
我真正需要做的是确定每种类型,这是我想做的
What I really need to do is determine this per type, here is what I'd like to do
HistoryCollection = Backbone.Model.extend({
model: function(item) {
return app.models[item.type]; } })
在我 fork Backbone 来实现这个之前有什么想法吗?(即一个可以带函数的集合模型属性)
Any ideas before I fork Backbone to implement this? (i.e. a collection model attribute being able to take a function)
推荐答案
在萤火虫中玩耍……想出了一种方法,您可以覆盖集合的解析方法而不是指定模型.您的解析实现基本上变成了一个简单的工厂,用于用您想要的模型填充集合:
Playing around in firebug.. came up with an approach where you can override the parse method of collection instead of specifying the model. Your parse implementation basically becomes a simple factory for filling the collection with models that you want:
var BaseModel = Backbone.Model.extend({
meth: function(){ return 'Base method'; },
});
var SubModel = BaseModel.extend({
meth: function(){ return 'Sub1 method'; }
});
var SubModel2 = BaseModel.extend({
meth: function(){ return 'Sub2 method'; }
});
var ModelCollection = Backbone.Collection.extend({
parse: function(data){
var self = this;
data.forEach(function(item){
switch(item.type){
case 1:
self.add(new SubModel(data));
break;
case 2:
self.add(new SubModel2(data));
break;
default:
self.add(new BaseModel(data))
}
});
}
});
//Example Use
x = new ModelCollection;
x.parse([{type: 1},{type: 2}, {type: 99}]);
x.map(function(e){ return e.meth();});
这篇关于具有特定类型的 Backbone.Js 集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!