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

Base model in Backbone JS access child data

我想在 Backbone 中创建一个基础模型 class,这样我的所有其他模型都可以扩展这个基础模型 class。在基础 class 中的某个点,我希望能够通过扩展 class.

访问数据集

例如,假设我的基础 class 是:

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'];
});

这能实现吗?

好问题!

我会建议您查看 Backbone 的 extend 方法,它与 Underscore 的扩展不同。

extend 中的第二个参数是 "static property",因此您无法通过实例方法访问它。

Here 正在运行 fiddle,它将提供基本结构。

源代码

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();