如何防止多次将相同的JSON对象或模型添加到集合中?

时间:2013-04-05 04:55:53

标签: backbone.js

我通过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对象添加/更新一次到集合。 感谢。

2 个答案:

答案 0 :(得分: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就是为什么你会看到两个代码。

答案 1 :(得分:0)

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