[Pkg-javascript-commits] [backbone] 276/281: check for duplicate models/ids

Jonas Smedegaard js at moszumanska.debian.org
Sat May 3 17:02:22 UTC 2014


This is an automated email from the git hooks/post-receive script.

js pushed a commit to tag 0.9.0
in repository backbone.

commit 50e8103fdfb684d08dfa3fa17aafa4dd7e010254
Author: Brad Dunbar <dunbarb2 at gmail.com>
Date:   Mon Jan 30 15:24:41 2012 -0500

    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 f652cff..0f72184 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 6aa7bb9..9c8a3c3 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}]); });
+  });
+
 });

-- 
Alioth's /usr/local/bin/git-commit-notice on /srv/git.debian.org/git/pkg-javascript/backbone.git



More information about the Pkg-javascript-commits mailing list