Search code examples
javascriptbackbone.js

Base model in Backbone JS access child data


I want to create a base model class in Backbone such that all my other models extend this base class. At some point in the base class, I want to be able to access the data set by the extending class.

For example, say my base class is:

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

can this be achieved?


Solution

  • Great question!

    I will advise you to look into Backbone's extend method wich differs from Underscore's extend.

    The second parameter in extend is "static property" so you cannot access it from withing instance method.

    Here is and working fiddle which will provide basic structure.

    Source code

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