简体   繁体   English

Backbone.js引导程序,带有一组JSON对象

[英]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. 我正在尝试使用JSON对象数组来引导骨干集合,如下面的代码所示。 However, when I try and call reset on the collection object I get an error from backbone - Uncaught TypeError: undefined is not a function . 但是,当我尝试在集合对象上调用reset时,我从主干上得到一个错误 - Uncaught TypeError: undefined is not a function

If I change the JSON array to an array of Users.UserModel objects then it works. 如果我将JSON数组更改为Users.UserModel对象数组,那么它可以工作。 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 . 我一定是失去了一些东西在收集基本initialization方法或类似的东西为我所看到的实际上并不包含太多的代码比调用的所有例子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) (我正在使用coffeescript btw,但那是无关紧要的)

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). 我只想到了这一点,我将我的代码逐步调整到了出现错误的backbone.js文件中,发现它发生在第570行(不是缩小的obv)。 Where the collection was trying to use it's own model property using this.model it was throwing the undefinded error. 集合试图使用它自己的model属性使用this.model它抛出了未找到的错误。

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! 当我回去查看我的代码时,我意识到我在模型之前声明了集合,所以当我设置集合的model属性时,它将其设置为undefined!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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