Created
September 22, 2020 15:24
-
-
Save smailliwcs/d6391716c16aac28d02787b6626cbc39 to your computer and use it in GitHub Desktop.
Knockout extender: coalesce
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
1 | |
2 | |
1 | |
1 | |
3 | |
4 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment