Skip to content Skip to sidebar Skip to footer

Declaring Variables On A Backbone Model Without Setting Defaults

I'm just starting out with backbone.js and I'm looking for a way of declaring fields on a model without having to provide defaults. It's really just for reference, so that when I s

Solution 1:

The defaults are really for "fields" or data that is transferred back and forth from the server as part of the json.

If you just want to create some member variables as part of the Model, which are proprietary and not going to be sent back and forth to the server, then you can declare them a) on the object itself or b) in the initialize method (called during construction), and they can be passed in as part of opts:

varWidget = Backbone.Model.extend({

    widgetCount: 0,

    defaults: {
        id: null,
        name: null
    }

    initialize: function(attr, opts) {
       // attr contains the "fields" set on the model// opts contains anything passed in after attr// so we can do things like thisif( opts && opts.widgetCount ) {
          this.widgetCount = opts.widgetCount;
       }
    }
});

var widget = newWidget({name: 'the blue one'}, {widgetCount: 20});

Keep in mind that if you declare objects or arrays on the class, they are essentially constants and changing them will modify all instances:

varWidget = Backbone.Model.extend({

    someOpts: { one: 1, two: 2},

    initialize: function(attr, opts) {
       // this is probably not going to do what you want because it will// modify `someOpts` for all Widget instances.this.someOpts.one = opts.one; 
    }
});

Post a Comment for "Declaring Variables On A Backbone Model Without Setting Defaults"