Skip to content

Commit 2a33522

Browse files
committed
Implement reset option for model.set
1 parent 82bf61e commit 2a33522

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

backbone.js

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -490,6 +490,7 @@
490490
// Extract attributes and options.
491491
var unset = options.unset;
492492
var silent = options.silent;
493+
var reset = options.reset;
493494
var changes = [];
494495
var changing = this._changing;
495496
this._changing = true;
@@ -515,6 +516,16 @@
515516
unset ? delete current[attr] : current[attr] = val;
516517
}
517518

519+
if (reset) {
520+
for (var currAttr in current) {
521+
if (!(currAttr in attrs)) {
522+
delete current[currAttr];
523+
changes.push(currAttr);
524+
changed[currAttr] = void 0;
525+
}
526+
}
527+
}
528+
518529
// Update the `id`.
519530
if (this.idAttribute in attrs) this.id = this.get(this.idAttribute);
520531

test/model.js

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -293,6 +293,31 @@
293293
assert.equal(a.id, undefined, 'Unsetting the id should remove the id property.');
294294
});
295295

296+
QUnit.test('set with reset option', function(assert) {
297+
assert.expect(8);
298+
var a = new Backbone.Model({id: 'id', foo: 1, bar: 2});
299+
var changeFooCount = 0;
300+
var changeBarCount = 0;
301+
var changeBazCount = 0;
302+
var changeIdCount = 0;
303+
a.on('change:foo', function() { changeFooCount += 1; });
304+
a.on('change:bar', function() { changeBarCount += 1; });
305+
a.on('change:baz', function() { changeBazCount += 1; });
306+
a.on('change:id', function() { changeIdCount += 1; });
307+
a.set({foo: 2, bar: 2, baz: 3}, {reset: true});
308+
assert.equal(a.get('foo'), 2, 'Foo should have changed.');
309+
assert.equal(changeFooCount, 1, 'Change count should have incremented.');
310+
311+
assert.equal(a.get('id'), void 0, 'Id should have be unset');
312+
assert.equal(changeIdCount, 1, 'Change count should have incremented.');
313+
314+
assert.equal(a.get('bar'), 2, 'Bar should NOT have changed');
315+
assert.equal(changeBarCount, 0, 'Change count should NOT have incremented.');
316+
317+
assert.equal(a.get('baz'), 3, 'Baz should have be set');
318+
assert.equal(changeBazCount, 1, 'Change count should have incremented.');
319+
});
320+
296321
QUnit.test('#2030 - set with failed validate, followed by another set triggers change', function(assert) {
297322
var attr = 0, main = 0, error = 0;
298323
var Model = Backbone.Model.extend({

0 commit comments

Comments
 (0)