documentcloud/backbone — Issue #814: Collections: initialize passed models after Collection got initialized
Author: gr2m
Created: 2011-12-24 11:37:46+00:00
State: open

I want to suggest a slight change. In `Backbone.Collection`, instead of

```Javascript
if (models) this.reset(models, {silent: true});
this.initialize.apply(this, arguments);
```

I'd like to suggest

```Javascript
this.initialize.apply(this, arguments);
if (models) this.reset(models, {silent: true});
```

All tests are still passing.

Why? Because otherwise the passed models get initialized before the collection itself gets initialized. My specific problem:

I can pass a parent to a collection as an option:

```CoffeeScript
parent = new App.Models.Base id: 'parent/123'
children = new App.Collections.Base [{id: 'child/1'},{id: 'child/2'}], parent: parent
```

If the parent get's destroyed, the children should get destroyed as well. I could put this logic into `App.Collections.Base` but some models have a parent without belonging to a collection (1:1 relation), so I need to put this logic into `App.Models.Base`.

To achieve this, I bind the model to its parent's destroy event, in case a parent is present.

```CoffeeScript
@parent()?.bind 'destroy', (model, collection, options) =>
delete options.success
delete options.error
@destroy options
```

`@parent()` method returns `options.parent` from the Model initialization or `options.parent` from Model's Collection initialization.

The problem is, the collection doesn't have a parent until it is funny initialized, that's why I would like to initialize the passed models after the collection got initialized.

Or is there any reason to keep it the way it is right now?