From 50e8103fdfb684d08dfa3fa17aafa4dd7e010254 Mon Sep 17 00:00:00 2001 From: Brad Dunbar Date: Mon, 30 Jan 2012 15:24:41 -0500 Subject: [PATCH] check for duplicate models/ids --- backbone.js | 8 ++++---- test/collection.js | 7 +++++++ 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/backbone.js b/backbone.js index f652cff1..0f72184a 100644 --- a/backbone.js +++ b/backbone.js @@ -470,7 +470,7 @@ // Add a model, or list of models to the set. Pass **silent** to avoid // firing the `add` event for every new model. add: function(models, options) { - var i, index, length, model, cids = {}; + var i, index, length, model, cids = {}, ids = {}; options || (options = {}); models = _.isArray(models) ? models.slice() : [models]; @@ -480,10 +480,11 @@ if (!(model = models[i] = this._prepareModel(models[i], options))) { throw new Error("Can't add an invalid model to a collection"); } - var hasId = model.id != null; - if (this._byCid[model.cid] || (hasId && this._byId[model.id])) { + if (cids[cid = model.cid] || this._byCid[cid] || + (((id = model.id) != null) && (ids[id] || this._byId[id]))) { throw new Error("Can't add the same model to a collection twice"); } + cids[cid] = ids[id] = model; } // Listen to added models' events, and index models for lookup by @@ -492,7 +493,6 @@ (model = models[i]).on('all', this._onModelEvent, this); this._byCid[model.cid] = model; if (model.id != null) this._byId[model.id] = model; - cids[model.cid] = true; } // Insert models into the collection, re-sorting if needed, and triggering diff --git a/test/collection.js b/test/collection.js index 6aa7bb9d..9c8a3c32 100644 --- a/test/collection.js +++ b/test/collection.js @@ -527,4 +527,11 @@ $(document).ready(function() { equal(col.length, 0); }); + test("Collection: multiple copies of the same model", function() { + var col = new Backbone.Collection(); + var model = new Backbone.Model(); + raises(function() { col.add([model, model]) }); + raises(function() { col.add([{id: 1}, {id: 1}]); }); + }); + });