recipeswithbackbone / recipeswithbackbone.github.com

Marketing site for the best damn backbone.js book evar
23 stars 1 forks source link

Trouble resetting a collection at initialization #51

Closed bemurphy closed 12 years ago

bemurphy commented 12 years ago

I'm working through the Reduced Models and Collections pattern in an app I have, and have a problem.

The call to this.reset(data) at initialization time results in 0 models present on the collection. However, when I log the data, I can see a 3 element array. I also assign the data to a global and then use it for a manual reset in console after the fact, and then the collection instance properly shows 3 models.

Do you know of any tricks/hangups when it comes to resetting a collection upon initialization? It feels like I'm fighting against some internal Backbone lifecycle flow on collections.

bemurphy commented 12 years ago

Aha, as usual, reading the source helps. The problem is the example initially passes in [] for a blank collection. However, the Collection construction function calls initialize and then performs a reset if the initial models data was provided:

https://github.com/documentcloud/backbone/blob/c4297e5e2eec66e5b2bbefe3dfa4b9a112199871/backbone.js#L559

Passing undefined as the argument instead of [] did the trick.

ngauthier commented 12 years ago

Yep. I get caught by that all the time. I often find myself doing new Collection(null, opts).