Backbone.js的收集特定类型 [英] Backbone.Js Collection with Specific Types

查看:78
本文介绍了Backbone.js的收集特定类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个BackboneJS集合称为历史可以包含几个骨干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];   } })

在我叉骨干任何想法来实现这一点? (即集合模型属性能够采取一个功能)

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屋!

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