Fix for adding models with custom set methods to collections, issue #539

This commit is contained in:
Alex Graul
2011-10-29 13:23:01 -04:00
parent 32ae113298
commit 567e0a3c2d
2 changed files with 28 additions and 1 deletions

View File

@@ -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;
}

View File

@@ -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([