From 2a3352253c2442739476b6814d4db74621a7b4fb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luiz=20Am=C3=A9rico?= Date: Sun, 20 Nov 2016 10:27:02 -0300 Subject: [PATCH] Implement reset option for model.set --- backbone.js | 11 +++++++++++ test/model.js | 25 +++++++++++++++++++++++++ 2 files changed, 36 insertions(+) diff --git a/backbone.js b/backbone.js index fdd7d3a2e..7161201d4 100644 --- a/backbone.js +++ b/backbone.js @@ -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; @@ -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); diff --git a/test/model.js b/test/model.js index b3092df7f..203ebb2d4 100644 --- a/test/model.js +++ b/test/model.js @@ -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({