Reputation: 3044
Reading through the docs, I see that you can replace the constructor for Backbone's extend on a model class. But what's the difference between doing this vs. doing it on the initialize method? Aren't both called when you use new
?
var Library = Backbone.Model.extend({
constructor: function() {
this.books = new Books();
Backbone.Model.apply(this, arguments);
},
parse: function(data, options) {
this.books.reset(data.books);
return data.library;
}
});
vs.
var Library = Backbone.Model.extend({
initialize: function() {
this.books = new Books();
Backbone.Model.apply(this, arguments);
},
parse: function(data, options) {
this.books.reset(data.books);
return data.library;
}
});
Upvotes: 1
Views: 1520
Reputation: 7946
"constructor" runs before Backbone sets up the structure.
"initialize" is called inside the structure's constructor function.
In other words if you need to add anything to the object before Backbone sets up the structure you might want to use "constructor". If you need to add something to your object after that Backbone sets up the structure you can use "initialize".
From: https://github.com/jashkenas/backbone/issues/720
Upvotes: 2