diff --git a/backbone.js b/backbone.js index 6005ce04..8667e65c 100644 --- a/backbone.js +++ b/backbone.js @@ -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; diff --git a/test/collection.js b/test/collection.js index dfbfbadb..58daca24 100644 --- a/test/collection.js +++ b/test/collection.js @@ -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'});