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