I have the following in test.html:
<script>
var Foo = Backbone.Model.extend({
initialize: function(options) {
console.log('hello!');
}
});
var Bar = Backbone.Collection.extend({
model: Foo
});
var m = new Bar({});
</script>
As it turns out, when the variable m is initialized, the initialize function of Foo is called. Thus, in the Firebug console, I get ‘hello!’. When I comment out the line:
model: Foo,
There is no ‘hello!’ in the console output. Thus, declaring a model for a collection calls that model’s initialize function. I think this behavior is a bit silly. I haven’t read through backbones code, but is there a reason for this?
Well, there’s nothing wrong with the behaviour of the code.
When you pass the model in the collection definition, you specify that every model in that collection will be of type
Foo.When you initialize the collection
new Bar({}), you pass a model to the collection (although, as @alexanderb stated, I think that the collections expects an array as a first argument) and it initializes it, thus outputting'hello!'.For example, if you do not pass any models to the collection constructor :
there will be no console output, and on the other hand, if you would pass an array of objects, then the collection would initialize all of the provided models :