具有特定类型的 Backbone.Js 集合
我有一个名为 History 的 BackboneJS 集合,它可以包含多个 Backbone JS 模型之一(从 HistoryItem 扩展,而 HistoryItem 又从 Backbone.Model 扩展),我试图找到一种在加载时重新创建它的方法,不幸的是,BackboneJS 集合似乎只能指定在特定模型上,例如
HistoryCollection = Backbone.Model.extend({
model: app.models.HistoryItem
})
我真正需要做的是确定每种类型,这就是我想要做的
HistoryCollection = Backbone.Model.extend({
model: function(item) {
return app.models[item.type]; } })
在我分叉 Backbone 来实现这个之前有什么想法吗? (即集合模型属性能够接受函数)
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]; } })
Any ideas before I fork Backbone to implement this? (i.e. a collection model attribute being able to take a function)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在 firebug 中玩弄......想出了一种方法,您可以覆盖集合的解析方法而不是指定模型。您的解析实现基本上成为一个简单的工厂,用于用您想要的模型填充集合:
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:
恕我直言,我更喜欢使用集合中的模型方法:
或使用代理模型:
IMHO, I prefer to play with the model method in the collection:
or using a proxy model:
我刚刚实现了此功能,并从 Jake Dempsey 的建议开始,但是您实际上需要重写集合中的不同方法。这是我使用的代码:
请注意,它是一个私有(ish)方法,因此升级 Backbone 时要记住一些事情。
I've just implemented this feature and started off with Jake Dempsey's advice, however you actually need to override a different method in the collection. This is the code I used:
Note that it is a private(ish) method so something to keep in mind when upgrading Backbone.