How to prevent adding same JSON object or model to collection multiple times?

Asked By: Anonymous

I get JSON data via ajax, then want to add these data to collection. I want to add/update new/existing objects to collection. I did it in two ways. Both are not working, and I kind of know why they are not working. But there must be solution for that.
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});

Result 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});

Result library.length = 2

I do want to add/update same model/JSON object only once to collection.
Thanks.


Solution

Answered By: Anonymous

Your json has no id value, so Backbone does not know that they are the same when you add it twice.

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});

Or:

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});

Normally, you would not set the id on the client side, you would let the server assign an id when you first save the new model. But… the lack of an id is why you see two with your code.

techinplanet staff

techinplanet staff


Windows 10 Kaufen Windows 10 Pro Office 2019 Kaufen Office 365 Lizenz Windows 10 Home Lizenz Office 2019 Home Business Kaufen windows office 365 satın al follower kaufen instagram follower kaufen porno