From cb17cbbbe0183634202c3423c76fffd63ae93861 Mon Sep 17 00:00:00 2001 From: Rafael Weinstein Date: Mon, 14 Apr 2014 15:09:58 -0700 Subject: [PATCH] implement resolveFn in bindToInstance R=arv BUG= Review URL: https://codereview.appspot.com/87760044 --- src/observe.js | 11 ++++++++++- tests/test.js | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+), 1 deletion(-) diff --git a/src/observe.js b/src/observe.js index fd1b36b..8309cb0 100644 --- a/src/observe.js +++ b/src/observe.js @@ -1092,7 +1092,7 @@ }); } - Observer.bindToInstance = function(instance, name, observable) { + Observer.bindToInstance = function(instance, name, observable, resolveFn) { var privateName = name + '_'; var privateObservable = name + 'Observable_'; @@ -1103,6 +1103,15 @@ notify(instance, name, value, oldValue); }); + if (resolveFn && !areSameValue(oldValue, value)) { + var resolvedValue = resolveFn(oldValue, value); + if (!areSameValue(value, resolvedValue)) { + value = resolvedValue; + if (observable.setValue) + observable.setValue(value); + } + } + instance[privateName] = value; notify(instance, name, value, oldValue); diff --git a/tests/test.js b/tests/test.js index a42cf9b..a572b52 100644 --- a/tests/test.js +++ b/tests/test.js @@ -881,6 +881,38 @@ suite('PathObserver Tests', function() { root.c.observer.close(); }); + test('BindToInstance - resolveFn', function() { + function MyClass() {} + + Observer.createBindablePrototypeAccessor(MyClass.prototype, 'value'); + + var a = new MyClass; + var obj1 = { value: 2 }; + a.value = 1; + + var b = new MyClass; + b.value = 4; + var obj2 = { value: 3 }; + + function preferEven(val1, val2) { + if (val1 % 2) + return val2; + return val1; + } + + var bound1 = Observer.bindToInstance(a, 'value', + new PathObserver(obj1, 'value'), preferEven); + + var bound2 = Observer.bindToInstance(b, 'value', + new PathObserver(obj2, 'value'), preferEven); + + assert.strictEqual(a.value, 2); + assert.strictEqual(b.value, 4); + + bound1.close(); + bound2.close(); + }); + test('Bound Property', function() { function MyClass() {}