简体   繁体   中英

Backbone.js bootstrap with an array of JSON objects

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 model property using this.model it 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' model property it was setting it to undefined!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM