backbone.js - How to prevent adding same JSON object or model to collection multiple times? -
i json data via ajax, want add these data collection. want add/update new/existing objects collection. did in 2 ways. both not working, , kind of know why not working. there must solution that.
1)
var book = backbone.model.extend({}); var library = backbone.collection.extend({model: book}); var library = new library(); var bookjson = { title: "one thousand , 1 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 , 1 nights", author: "scheherazade" } library.add(book, {merge: true}); library.add(book, {merge: true});
result library.length = 2
i want add/update same model/json object once collection. thanks.
your json has no id
value, backbone not know same when add twice.
var book = backbone.model.extend({}); var library = backbone.collection.extend({model: book}); var library = new library(); var book = { id: 1, // 'id' default idattribute. title: "one thousand , 1 nights", author: "scheherazade" } library.add(book, {merge: true}); library.add(book, {merge: true});
or:
var book = backbone.model.extend({ idattribute: 'title' // might not thing use id, though. }); var library = backbone.collection.extend({model: book}); var library = new library(); var book = { title: "one thousand , 1 nights", author: "scheherazade" } library.add(book, {merge: true}); library.add(book, {merge: true});
normally, not set id on client side, let server assign id when first save new model. but... lack of id
why see 2 code.
Comments
Post a Comment