Fix bug causing mutations while merging with nested models

Again, I'm not a huge fan of this solution to the merge + defaults problem, but
this will work until somone more clever than I figures out what to do or we
reevaluate the whole existance checking ordeal.
This commit is contained in:
Casey Foster
2013-05-01 13:38:33 -05:00
parent 6b3e52cd9d
commit fd0cb9695d
2 changed files with 18 additions and 1 deletions

View File

@@ -251,7 +251,7 @@
this.attributes = {};
if (options.collection) this.collection = options.collection;
if (options.parse) attrs = this.parse(attrs, options) || {};
options._attrs = attrs;
options._attrs || (options._attrs = attrs);
if (defaults = _.result(this, 'defaults')) {
attrs = _.defaults({}, attrs, defaults);
}
@@ -685,6 +685,7 @@
if (remove) modelMap[existing.cid] = true;
if (merge) {
attrs = attrs === model ? model.attributes : options._attrs;
delete options._attrs;
existing.set(attrs, options);
if (sortable && !sort && existing.hasChanged(sortAttr)) sort = true;
}

View File

@@ -967,6 +967,22 @@ $(document).ready(function() {
equal(col.length, 1);
});
test('merge without mutation', function () {
var Model = Backbone.Model.extend({
initialize: function (attrs, options) {
if (attrs.child) {
this.set('child', new Model(attrs.child, options), options);
}
}
});
var Collection = Backbone.Collection.extend({model: Model});
var data = [{id: 1, child: {id: 2}}];
var collection = new Collection(data);
equal(collection.first().id, 1);
collection.set(data);
equal(collection.first().id, 1);
});
test("`set` and model level `parse`", function() {
var Model = Backbone.Model.extend({
parse: function (res) { return res.model; }