Skip to content

Commit

Permalink
Implement reset option for model.set
Browse files Browse the repository at this point in the history
  • Loading branch information
blikblum committed Jan 26, 2018
1 parent 82bf61e commit 2a33522
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
11 changes: 11 additions & 0 deletions backbone.js
Original file line number Diff line number Diff line change
Expand Up @@ -490,6 +490,7 @@
// Extract attributes and options.
var unset = options.unset;
var silent = options.silent;
var reset = options.reset;
var changes = [];
var changing = this._changing;
this._changing = true;
Expand All @@ -515,6 +516,16 @@
unset ? delete current[attr] : current[attr] = val;
}

if (reset) {
for (var currAttr in current) {
if (!(currAttr in attrs)) {
delete current[currAttr];
changes.push(currAttr);
changed[currAttr] = void 0;
}
}
}

// Update the `id`.
if (this.idAttribute in attrs) this.id = this.get(this.idAttribute);

Expand Down
25 changes: 25 additions & 0 deletions test/model.js
Original file line number Diff line number Diff line change
Expand Up @@ -293,6 +293,31 @@
assert.equal(a.id, undefined, 'Unsetting the id should remove the id property.');
});

QUnit.test('set with reset option', function(assert) {
assert.expect(8);
var a = new Backbone.Model({id: 'id', foo: 1, bar: 2});
var changeFooCount = 0;
var changeBarCount = 0;
var changeBazCount = 0;
var changeIdCount = 0;
a.on('change:foo', function() { changeFooCount += 1; });
a.on('change:bar', function() { changeBarCount += 1; });
a.on('change:baz', function() { changeBazCount += 1; });
a.on('change:id', function() { changeIdCount += 1; });
a.set({foo: 2, bar: 2, baz: 3}, {reset: true});
assert.equal(a.get('foo'), 2, 'Foo should have changed.');
assert.equal(changeFooCount, 1, 'Change count should have incremented.');

assert.equal(a.get('id'), void 0, 'Id should have be unset');
assert.equal(changeIdCount, 1, 'Change count should have incremented.');

assert.equal(a.get('bar'), 2, 'Bar should NOT have changed');
assert.equal(changeBarCount, 0, 'Change count should NOT have incremented.');

assert.equal(a.get('baz'), 3, 'Baz should have be set');
assert.equal(changeBazCount, 1, 'Change count should have incremented.');
});

QUnit.test('#2030 - set with failed validate, followed by another set triggers change', function(assert) {
var attr = 0, main = 0, error = 0;
var Model = Backbone.Model.extend({
Expand Down

0 comments on commit 2a33522

Please sign in to comment.