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!
Backbone. Backbone has been around for a long time, but it's still under steady and regular development. It's a good choice if you want a flexible JavaScript framework with a simple model for representing data and getting it into views.
You can use the Backbone. Model without jQuery, but Backbone.
Backbone is a JavaScript MVC library and that's a key difference. In the JavaScript MVC context, a framework usually means that you need to configure your code to get things done.
There is only method named "start" can be used to manipulate the Backbone. js history.
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()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With