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?
the
_prepareModelstacktrace line gives a hint that you have your model declared after your collection.You most likely have your code set up like this:
which is going to fail because
ListItemis not yet declared when you try to use it in your collection’smodelattribute. You are essentially setting the model attribute toundefined.You need to declare the model first:
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.