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

Javascriptbackbone.js

Javascript Problem Overview


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
   },

Javascript Solutions


Solution 1 - Javascript

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)

Solution 2 - Javascript

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionscreenm0nkeyView Question on Stackoverflow
Solution 1 - JavascriptBoyoView Answer on Stackoverflow
Solution 2 - JavascriptSudhir JonathanView Answer on Stackoverflow