I am attempting to bootstrap a backbone collection using an array of JSON objects like in the code below. However, when I try and call reset on the collection object I get an error from backbone – Uncaught TypeError: undefined is not a function.
If I change the JSON array to an array of Users.UserModel objects then it works. I must be missing something fundamental in the collection initialization method or something similar as all the examples I have seen don’t really contain much code than the call to reset.
class Users.UsersCollection extends Backbone.Collection
model: Users.UserModel
url: '/Users'
class Users.UserModel extends Backbone.Model
# document ready
$ ->
Users.userCollection = new Users.UsersCollection()
users = [
{ Id: 1, Username: 'dan', FirstName: 'Dan', LastName: 'Ormisher' },
{ Id: 1, Username: 'simon', FirstName: 'Simon', LastName: 'Lomax' },
{ Id: 1, Username: 'jon', FirstName: 'Jon', LastName: 'Swain' },
{ Id: 1, Username: 'martin', FirstName: 'Martin', LastName: 'Rue' }
]
Users.userCollection.reset(users)
(I’m using coffeescript btw, but that is irrelevant)
I just figured this out, I stepped through my code to the point in the backbone.js file where the error was happening, and found it was happening on line 570 (not minified obv). Where the collection was trying to use it’s own
modelproperty usingthis.modelit was throwing the undefinded error.When I went back and looked at my code, I realised I was declaring the collection before the model, so when I was setting the collections’
modelproperty it was setting it to undefined!