From 492d374b59600275a0a1a44d63d6dd21deac1c54 Mon Sep 17 00:00:00 2001 From: David Durman Date: Tue, 23 Apr 2013 20:05:10 +0200 Subject: [PATCH] trigger changes on all parent attributes --- README.md | 4 ++++ src/deep-model.js | 19 +++++++++++++++++++ test/deep-model.test.js | 4 ++++ 3 files changed, 27 insertions(+) diff --git a/README.md b/README.md index bdc6a08..3adabc8 100644 --- a/README.md +++ b/README.md @@ -46,6 +46,10 @@ Example code: console.log(val); }); + //... and all parent attributes as well + model.bind('change:user.name', function(model, val) { console.log(val); }); + model.bind('change:user', function(model, val) { console.log(val); }); + //Wildcards are supported model.bind('change:user.*', function() {}); diff --git a/src/deep-model.js b/src/deep-model.js index 55c19dd..b9a154e 100644 --- a/src/deep-model.js +++ b/src/deep-model.js @@ -225,6 +225,25 @@ } // } + // + // Flag triggered events so that they are not triggered more then once. + var triggered = {}; + _.each(changes, function(key) { + + var fields = key.split(separator); + + //Trigger change events for parent keys without wildcard (*) notation. + + for(var n = fields.length - 1; n > 0; n--) { + var parentKey = _.first(fields, n).join(separator); + + if (!triggered[parentKey]) { + this.trigger('change:' + parentKey, this, getNested(current, parentKey), options); + } + triggered[parentKey] = true; + } + }, this); + // } if (changing) return this; diff --git a/test/deep-model.test.js b/test/deep-model.test.js index bbd64ba..a39722f 100644 --- a/test/deep-model.test.js +++ b/test/deep-model.test.js @@ -262,6 +262,8 @@ test("set: Triggers model change:[attribute] events", function() { 'change:user.name.first', 'change:user.name.*', 'change:user.*', + 'change:user.name', + 'change:user', 'change' ]); })(); @@ -503,6 +505,8 @@ test("unset: Triggers model change:[attribute] events", function() { 'change:user.name.first', 'change:user.name.*', 'change:user.*', + 'change:user.name', + 'change:user', 'change' ]); })();