JSON不会直接填充主干集合

neu*_*v33 1 backbone.js backbone.js-collections

我有从服务器返回的JSON,我正在用它填充Backbone集合.

楷模

Person = Backbone.Model.extend({

});

PersonCollection = Backbone.Collection.extend({
    model: Person
});
Run Code Online (Sandbox Code Playgroud)

例如JSON-

var jsonString = "[
  { \"name\": \"Anna\", \"id\": 5 },
  { \"name\": \"Lina\", \"id\": 26 },
  { \"name\": \"Melissa\", \"id\": 55 }    
]"

var people = JSON.parse(jsonString); //people is now an array of 3 persons
Run Code Online (Sandbox Code Playgroud)

作品:

var personCollection = new PersonCollection();
for (var i = 0; i < people.length; i++) {
    personCollection.add(people[i]);
}
var personCollectionView = new PersonCollectionView({ collection:  personCollection});
Run Code Online (Sandbox Code Playgroud)

不起作用:(

var personCollectionView = new PersonCollectionView({ collection:  people});
Run Code Online (Sandbox Code Playgroud)

我的JSON返回一个模型数组,我不知道为什么我不能将这个数组直接传递给PersonCollectionView?在PersonCollection的parse方法中是否需要做一些事情,这样当给定一个模型数组时,它会将它转换为模型集合?

我确定我错过了什么.有人可以指出那是什么吗?

Jon*_*uin 5

您没有正确创建集合对象,请删除new关键字:

PersonCollection = Backbone.Collection.extend({
    model: Person
});
Run Code Online (Sandbox Code Playgroud)

然后,您可以创建JSON对象并将其传递给集合:

var people = JSON.parse(jsonString);
var personCollection = new PersonCollection(people);
Run Code Online (Sandbox Code Playgroud)

请注意,JSON.parse它使用小写并且jsonString语法不正确:

var jsonString = "[  { \"name\": \"Anna\", \"id\": 5 },  { \"name\": \"Lina\", \"id\": 26 },   { \"name\": \"Melissa\", \"id\": 55 }    ]";
Run Code Online (Sandbox Code Playgroud)

在这里查看工作演示.