Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between initialize and constructor on a backbone model

What's the difference between initialize and constructor on a backbone model.

When I extend a backbone model (ParentModel) I use the initialize method to set any default properties. But whenever I create a Model based on the ParentModel I use the constructor to to run any intial functionality. I do this because it works but someone at work asked me why I use both initialize and constructor and I didn't have a good answer apart from it works. I could spend time reading though the source code to figure it out but it seemed much easier to ask here and get the right answer.

var ParentModel = Backbone.Model.extend({   initialize : function() {     // code here   }, });   var Model = ParentModel.extend({   constructor : function (options) {     Backbone.Model.prototype.constructor.call(this, options);     // code here    }, 
like image 451
screenm0nkey Avatar asked Apr 12 '12 07:04

screenm0nkey


2 Answers

constructor runs before Backbone sets up the structure. initialize is called inside the structure's constructor function. So basically if you need to augment anything before Backbone sets up the structure, use constructor if you need to augment anything after Backbone sets up the structure use initialize.

(from a Github discussion on the subject)

like image 180
Boyo Avatar answered Sep 28 '22 07:09

Boyo


constructor is the function that Backbone uses to set itself up - creating the models, setting events, and doing all kinds of other setup. Be very careful about overriding this, because if you prevent Backbone code from running by overriding or shadowing the method, you'll get weird errors that are hard to debug.

initialize on the other hand is a function that Backbone calls on its objects once it's finished up with its internal plumbing. If you're not doing anything that's specifically intended to interfere with normal Backbone functionality, just use initialize.

If you're using CoffeeScript, it might be more intuitive to use constructor. (It is for me). Just make sure you always call super, though.

like image 31
Sudhir Jonathan Avatar answered Sep 28 '22 07:09

Sudhir Jonathan