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/d6391716c16aac28d02787b6626cbc39 to your computer and use it in GitHub Desktop.
Save smailliwcs/d6391716c16aac28d02787b6626cbc39 to your computer and use it in GitHub Desktop.
Knockout extender: coalesce
ko.extenders.coalesce = function (target, defaultValue) {
var result = ko.computed({
read: function () {
return target() === undefined ? ko.unwrap(defaultValue) : target();
},
write: function (value) {
target(value);
}
});
result.defaultValue = ko.computed(function () {
return ko.unwrap(defaultValue);
});
return result;
};
var x = ko.observable().extend({ coalesce: 1 });
console.log(x());
x(2);
console.log(x());
console.log(x.defaultValue());
x(undefined);
console.log(x());
var y = ko.observable(3);
var z = ko.observable().extend({ coalesce: y });
console.log(z());
y(4);
console.log(z());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment