From 2d02a3cfb626e2a605bb4049ffdae0810aa20e6a Mon Sep 17 00:00:00 2001 From: Jeremy Ashkenas Date: Tue, 17 Jan 2012 10:54:03 -0500 Subject: [PATCH] Fixes #861, better error message for adding invalid models to a collection. --- backbone.js | 5 ++++- test/collection.js | 33 ++++++++++++++++++++++++--------- 2 files changed, 28 insertions(+), 10 deletions(-) diff --git a/backbone.js b/backbone.js index f7d3b8d2..bb4ebf3b 100644 --- a/backbone.js +++ b/backbone.js @@ -457,9 +457,12 @@ models = slice.call(models); for (i = 0, length = models.length; i < length; i++) { var model = models[i] = this._prepareModel(models[i], options); + if (!model) { + 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])) { - throw new Error("Can't add the same model to a set twice"); + throw new Error("Can't add the same model to a collection twice"); } this._byCid[model.cid] = model; if (hasId) this._byId[model.id] = model; diff --git a/test/collection.js b/test/collection.js index 33e2d76d..29fc5457 100644 --- a/test/collection.js +++ b/test/collection.js @@ -138,26 +138,22 @@ $(document).ready(function() { }); test("Collection: can't add model to collection twice", function() { - try { + raises(function(){ // 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"); - } + }, "Can't add the same model to a collection twice"); }); test("Collection: can't add different model with same id to collection twice", function() { - var col = new Backbone.Collection; - try { + raises(function(){ + var col = new Backbone.Collection; col.add({id: 101}); col.add({id: 101}); ok(false, "duplicate; expected add to fail"); - } catch (e) { - equals(e.message, "Can't add the same model to a set twice"); - } + }, "Can't add the same model to a collection twice"); }); test("Collection: add model to multiple collections", function() { @@ -475,4 +471,23 @@ $(document).ready(function() { equals(col.length, 0); }); + test("#861, adding models to a collection which do not pass validation", function() { + raises(function() { + var Model = Backbone.Model.extend({ + validate: function(attrs) { + console.log(attrs.id); + if (attrs.id == 3) return "id can't be 3"; + } + }); + + var Collection = Backbone.Collection.extend({ + model: Model + }); + + var col = new Collection; + + col.add([{id: 1}, {id: 2}, {id: 3}, {id: 4}, {id: 5}, {id: 6}]); + }, "Can't add an invalid model to a collection"); + }); + });