Skip to content
This repository has been archived by the owner on Jul 10, 2018. It is now read-only.

Commit

Permalink
Fix for adding models with custom set methods to collections, issue j…
Browse files Browse the repository at this point in the history
  • Loading branch information
Alex Graul committed Oct 29, 2011
1 parent 32ae113 commit 567e0a3
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 1 deletion.
2 changes: 1 addition & 1 deletion backbone.js
Expand Up @@ -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;
}
Expand Down
27 changes: 27 additions & 0 deletions test/collection.js
Expand Up @@ -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([
Expand Down

0 comments on commit 567e0a3

Please sign in to comment.