Backbone JS中的基本模型访问子数据

时间:2015-03-12 18:14:26

标签: javascript backbone.js

我想在Backbone中创建一个基本模型类,以便我所有其他模型都扩展这个基类。在基类的某个时刻,我希望能够通过扩展类访问数据集。

例如,假设我的基类是:

var baseModel = Backbone.Model.extend({
    someFunc: function() {
        // This guy needs to operate on 'protected' array set my the extending model
    }
}, {
    protected: [] // this is to be set by the extending model
});

var extendingModel = baseModel.extend({

}, {
    protected: ['id', 'username'];
});

这可以实现吗?

1 个答案:

答案 0 :(得分:0)

很棒的问题!

我建议你研究Backbone的extend方法,它与Underscore的扩展不同。

extend中的第二个参数是"静态属性"所以你无法通过实例方法访问它。

Here是工作小提琴,它将提供基本结构。

源代码

var BaseModel = Backbone.Model.extend({
    someFunc: function() {
        // This guy needs to operate on 'protected' array set my the extending model
        $('.container').append(JSON.stringify(this.protected || 'something'));
    }
}, {
     // this is to be set by the extending model
});

var ExtendingModel = BaseModel.extend({
  protected: ['id', 'username']
}, {

});

var test = new ExtendingModel();

test.someFunc();


var ExtendingModel2 = BaseModel.extend({
  protected: ['anotherProp', 'ABC']
}, {

});
test1 = new ExtendingModel2();

test1.someFunc();

test3 = new BaseModel();
test3.someFunc();