我通过 ajax 获取 JSON 数据,然后想将这些数据添加到集合中。我想将新的/现有的对象添加/更新到集合中。我通过两种方式做到了。两者都不工作,我有点知道他们为什么不工作。但必须有解决方案。
1)
var Book = Backbone.Model.extend({});
var Library = Backbone.Collection.extend({model: Book});
var library = new Library();
var bookJSON = {
title: "One Thousand and One Nights",
author: "Scheherazade"
}
var book1 = new Book(bookJSON);
var book2 = new Book(bookJSON);
library.add(book1, {merge: true});
library.add(book2, {merge: true});
结果library.length = 2
2)
var Book = Backbone.Model.extend({});
var Library = Backbone.Collection.extend({model: Book});
var library = new Library();
var book = {
title: "One Thousand and One Nights",
author: "Scheherazade"
}
library.add(book, {merge: true});
library.add(book, {merge: true});
结果library.length = 2
我确实只想将相同的模型/JSON 对象添加/更新一次以进行收集。谢谢。