Skip to content
This repository has been archived by the owner on Mar 13, 2018. It is now read-only.

Commit

Permalink
implement resolveFn in bindToInstance
Browse files Browse the repository at this point in the history
  • Loading branch information
rafaelw committed Apr 14, 2014
1 parent dac782e commit cb17cbb
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 1 deletion.
11 changes: 10 additions & 1 deletion src/observe.js
Expand Up @@ -1092,7 +1092,7 @@
});
}

Observer.bindToInstance = function(instance, name, observable) {
Observer.bindToInstance = function(instance, name, observable, resolveFn) {
var privateName = name + '_';
var privateObservable = name + 'Observable_';

Expand All @@ -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);

Expand Down
32 changes: 32 additions & 0 deletions tests/test.js
Expand Up @@ -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() {}

Expand Down

0 comments on commit cb17cbb

Please sign in to comment.