Backbone Collection.reset() doesn't work on extended Collections
backbone.js, collections, javascript
Solution
the `_prepareModel` stacktrace line gives a hint that you have your model declared after your collection.
You most likely have your code set up like this:
class App.Collections.List extends Backbone.Collection
model: App.Models.ListItem
class App.Models.ListItem extends Backbone.Model
which is going to fail because `ListItem` is not yet declared when you try to use it in your collection's `model` attribute. You are essentially setting the model attribute to `undefined`.
You need to declare the model first:
class App.Models.ListItem extends Backbone.Model
class App.Collections.List extends Backbone.Collection
model: App.Models.ListItem
Note that this is not a limitation in CoffeeScript or Backbone. This is a JavaScript behavior caused by the use of object literals. The value of an object literal key/value pair is evaluated immediately, which means it must exist or it will be returned as undefined or some other error thrown.
Problem
I have a Backbone collection ``` jQuery -> class App.Collections.List extends Backbone.Collection model: App.Models.ListItem ``` I am trying to initialize the collection on page load: ``` var list = new App.Collections.List; list.reset(<%= @data.to_json.html_safe %>) ``` This throws a JS error in the backbone lib. ``` Uncaught TypeError: undefined is not a function application.js:597 f.extend._prepareModel application.js:597 f.extend.add application.js:591 f.extend.reset application.js:595 (anonymous function) ``` However, if i change the code to: ``` var list = new Backbone.Collections; list.reset(<%= @data.to_json.html_safe %>) ``` The reset works, and the collection is populated -- thought the objects in the Collection don't appear to know that they should be ListItem objects. Do I have to do something special to all a reset of my custom Collection?