Collection.add should fail if duplicate id/cid exists

This commit is contained in:
Niall Smart
2011-06-13 18:11:04 -07:00
parent 2620c6a5ed
commit 0853866aab
2 changed files with 20 additions and 1 deletions

View File

@@ -582,7 +582,7 @@
options || (options = {});
model = this._prepareModel(model, options);
if (!model) return false;
var already = this.getByCid(model);
var already = this.getByCid(model) || this.get(model);
if (already) throw new Error(["Can't add the same model to a set twice", already.id]);
this._byId[model.id] = model;
this._byCid[model.cid] = model;

View File

@@ -95,6 +95,25 @@ $(document).ready(function() {
equals(atCol.last(), h);
});
test("Collection: add model to collection twice", function() {
try {
// same id, different cid
col.add({id: a.id, label: a.label});
ok(false, "duplicate; expected add to fail");
} catch (e) {
equals(e.message, "Can't add the same model to a set twice,3");
}
try {
// no id, same cid
var a2 = new Backbone.Model({label: a.label});
a2.cid = a.cid
col.add(a2);
ok(false, "duplicate; expected add to fail");
} catch (e) {
equals(e.message, "Can't add the same model to a set twice,3");
}
});
test("Collection: add model to multiple collections", function() {
var counter = 0;
var e = new Backbone.Model({id: 10, label : 'e'});