Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone.js custom constructor?

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!

like image 221
fancy Avatar asked May 01 '12 14:05

fancy


People also ask

Does anyone use Backbone JS?

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.

Does Backbone need jQuery?

You can use the Backbone. Model without jQuery, but Backbone.

Is Backbone a MVC?

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.

What is the only method available in the backbone JS history?

There is only method named "start" can be used to manipulate the Backbone. js history.


1 Answers

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

like image 178
JMM Avatar answered Oct 17 '22 00:10

JMM