From 3d9b9cbc1d842130d991a1b01e8fe837ddb1b6c3 Mon Sep 17 00:00:00 2001 From: Tom Hicks Date: Sun, 11 May 2014 21:17:21 +0100 Subject: [PATCH 1/2] test case for PR #60 demonstrates issue where setting a value inside a nested array erroneously triggers and add event, when no item has been added --- test/nested-model.js | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/test/nested-model.js b/test/nested-model.js index 6610b50..36d8e50 100644 --- a/test/nested-model.js +++ b/test/nested-model.js @@ -301,6 +301,24 @@ $(document).ready(function() { deepEqual(doc.get('addresses[0].areaCodes'), []); }); + test("#set() 1-1 inside an array should not trigger the add event", function () { + var entity = new Klass({ + names: [ + { first: 'John' } + ] + }); + + var callbackFired = false; + + entity.on('add:names', function () { + callbackFired = true; + }); + + entity.set('names[0].first', 'Steve'); + + ok(!callbackFired, "Callback should not have been fired"); + }); + // ----- TO_JSON -------- From 07683a77061985b1798e3df41a05f4d5c5dae8ed Mon Sep 17 00:00:00 2001 From: Tom Hicks Date: Sun, 11 May 2014 23:54:06 +0100 Subject: [PATCH 2/2] fix for issue #60 and #117 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Checks whether or not the set method call will add a new item to a nested array. If not, the ‘add’ event is not triggered where previously it would. --- backbone-nested.js | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/backbone-nested.js b/backbone-nested.js index afc7c65..0eac107 100644 --- a/backbone-nested.js +++ b/backbone-nested.js @@ -245,6 +245,13 @@ var fullPathLength = attrPath.length; var model = this; + var shouldTriggerAdd; + + var parentPath = Backbone.NestedModel.createAttrStr(_.initial(attrPath)); + if (parentPath && _.isArray(this.get(parentPath)) && + this.get(Backbone.NestedModel.createAttrStr(attrPath)) === undefined) { + shouldTriggerAdd = true; + } Backbone.NestedModel.walkPath(newAttrs, attrPath, function(val, path, next){ var attr = _.last(path); @@ -314,7 +321,7 @@ model._delayedChange(attrStr, val[attr], opts); } - if (_.isArray(val[attr])){ + if (_.isArray(val[attr]) && shouldTriggerAdd){ model._delayedTrigger('add:' + attrStr, model, val[attr]); } }