0

我通过 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 对象添加/更新一次以进行收集。谢谢。

4

2 回答 2

4

你的 json 没有任何id价值,所以 Backbone 在你添加两次的时候并不知道它们是一样的。

var Book = Backbone.Model.extend({});
var Library = Backbone.Collection.extend({model: Book});
var library = new Library();
var book = {
  id: 1,   // 'id' is the default idAttribute.
  title: "One Thousand and One Nights",
  author: "Scheherazade"
}
library.add(book, {merge: true});
library.add(book, {merge: true});

或者:

var Book = Backbone.Model.extend({
    idAttribute: 'title'  // might not be a good thing to use as an id, though.
});
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});

通常,您不会在客户端设置 id,而是让服务器在首次保存新模型时分配一个 id。但是......缺少一个id是为什么你在你的代码中看到两个。

于 2013-04-05T05:35:28.957 回答
0

您的代码似乎没问题,您使用的是backbone.js 0.9.9 还是更高版本?在 0.9.9 版本中添加了合并选项。

于 2013-04-05T05:31:51.087 回答