From 567e0a3c2ddc6b2e66ee1258bfb7dd3b9ce1bbb6 Mon Sep 17 00:00:00 2001 From: Alex Graul Date: Sat, 29 Oct 2011 13:23:01 -0400 Subject: [PATCH] Fix for adding models with custom set methods to collections, issue #539 --- backbone.js | 2 +- test/collection.js | 27 +++++++++++++++++++++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/backbone.js b/backbone.js index ebb049791..a7dd4045a 100644 --- a/backbone.js +++ b/backbone.js @@ -568,7 +568,7 @@ if (!(model instanceof Backbone.Model)) { var attrs = model; model = new this.model(attrs, {collection: this}); - if (model.validate && !model._performValidation(attrs, options)) model = false; + if (model.validate && !model._performValidation(model.attributes, options)) model = false; } else if (!model.collection) { model.collection = this; } diff --git a/test/collection.js b/test/collection.js index df449145b..1ff11fdfd 100644 --- a/test/collection.js +++ b/test/collection.js @@ -44,6 +44,33 @@ $(document).ready(function() { equals(col.get(101), model); }); + test("Collection: add model with attributes modified by set", function() { + var CustomSetModel = Backbone.Model.extend({ + defaults: { + number_as_string: null //presence of defaults forces extend + }, + + validate: function (attributes) { + if (!_.isString(attributes.num_as_string)) { + return 'fail'; + } + }, + + set: function (attributes, options) { + if (attributes.num_as_string) { + attributes.num_as_string = attributes.num_as_string.toString(); + } + Backbone.Model.prototype.set.call(this, attributes, options); + } + }); + + var CustomSetCollection = Backbone.Collection.extend({ + model: CustomSetModel + }); + var col = new CustomSetCollection([{ num_as_string: 2 }]); + equals(col.length, 1); + }); + test("Collection: update index when id changes", function() { var col = new Backbone.Collection(); col.add([