Backbone.js custom constructor?
backbone.js, javascript
Solution
If you really want to override the constructor, pass a `constructor` property to `Backbone.Model.extend()`, e.g.:
var Klass = Backbone.Model.extend( {
constructor : function ( attributes, options ) {
// ...
}
} );
If you want to call the built-in constructor from your custom constructor, you can do something like:
var Klass = Backbone.Model.extend( {
constructor : function ( attributes, options ) {
Backbone.Model.apply( this, arguments );
}
} );
Or if you don't want to have to repeat the name of the variable containing the parent class all over the sub class, or you don't want to worry about the value of that variable changing, you can do something like the following:
var Klass;
var parent_klass = Backbone.Model.prototype;
( function ( parent_klass ) {
Klass = parent_klass.constructor.extend( {
constructor : function ( attributes, options ) {
parent_klass.constructor.apply( this, arguments );
}
} );
} )( parent_klass );
Or if you prefer the way @Claude suggests, but repeating the sub class variable name within the sub class instead of the parent class var name:
var Klass = Backbone.Model.extend(
{
constructor : function ( attributes, options ) {
Klass.parent_klass.constructor.apply( this, arguments );
}
},
{
parent_klass : Backbone.Model.prototype
}
);
If you want more advice than that, you'll have to be more specific about what you want to accomplish.
Anything that you just want to do after the built-in constructor functionality, you should probably do in `initialize()`.
Problem
I'm looking for some examples for creating a custom constructor on my models. I want the structure the model/data differently then just setting it as attributes. Can somebody show me some basic example of how to do this? Thanks!