Skip to content

Instantly share code, notes, and snippets.

@smailliwcs
Created September 22, 2020 15:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save smailliwcs/04ffc8e52365185777e5f5edce9c78b5 to your computer and use it in GitHub Desktop.
Save smailliwcs/04ffc8e52365185777e5f5edce9c78b5 to your computer and use it in GitHub Desktop.
Knockout extender: observe
ko.extenders.observe = function (target, source) {
target(source);
var result = ko.computed({
read: function () {
return target()();
},
write: function (value) {
target()(value);
}
});
result.observe = function (source) {
target(source);
};
return result;
};
var x = ko.observable(10);
var y = ko.observable(20);
var z = ko.observable().extend({ observe: x });
console.log(z());
x(11);
console.log(z());
y(21);
console.log(z());
z.observe(y);
console.log(z());
x(12);
console.log(z());
y(22);
console.log(z());
z(30);
console.log(z());
console.log(y());
10
11
11
21
21
22
30
30
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment