Given a computed property
vm.checkedValueCount = ko.computed(function(){
var observables = getCurrentValues(); //an array of ko.observable[]
return _.filter
This answer is conceptually the same as the one @josh gave, but presented as a more generic wrapper. Note: this version is for a 'writeable' computed.
I'm using Typescript so I've included the ts.d definition first. So ignore this first part if not relevant to you.
interface KnockoutStatic
{
notifyingWritableComputed(options: KnockoutComputedDefine, context ?: any): KnockoutComputed;
}
observable
that always causes subscribers to be notified - even if no observables were updated as a result of the write
callJust replace function
with function(options, context)
if you don't use Typescript.
ko.notifyingWritableComputed = function (options: KnockoutComputedDefine, context)
{
var _notifyTrigger = ko.observable(0);
var originalRead = options.read;
var originalWrite = options.write;
// intercept 'read' function provided in options
options.read = () =>
{
// read the dummy observable, which if updated will
// force subscribers to receive the new value
_notifyTrigger();
return originalRead();
};
// intercept 'write' function
options.write = (v) =>
{
// run logic provided by user
originalWrite(v);
// force reevaluation of the notifyingWritableComputed
// after we have called the original write logic
_notifyTrigger(_notifyTrigger() + 1);
};
// just create computed as normal with all the standard parameters
return ko.computed(options, context);
}
The main use case for this is when you are updating something that would not otherwise trigger a change in an observable that is 'visited' by the read
function.
For instance I am using LocalStorage to set some values, but there is no change to any observable to trigger re-evaluation.
hasUserClickedFooButton = ko.notifyingWritableComputed(
{
read: () =>
{
return LocalStorageHelper.getBoolValue('hasUserClickedFooButton');
},
write: (v) =>
{
LocalStorageHelper.setBoolValue('hasUserClickedFooButton', v);
}
});
Note that all I needed to change was ko.computed
to ko.notifyingWritableComputed
and then everything takes care of itself.
When I call hasUserClickedFooButton(true)
then the 'dummy' observable is incremented forcing any subscribers (and their subscribers) to get the new value when the value in LocalStorage is updated.
(Note: you may think the notify: 'always'
extender is an option here - but that's something different).
There is an additional solution for a computed observable that is only readble:
ko.forcibleComputed = function(readFunc, context, options) {
var trigger = ko.observable().extend({notify:'always'}),
target = ko.computed(function() {
trigger();
return readFunc.call(context);
}, null, options);
target.evaluateImmediate = function() {
trigger.valueHasMutated();
};
return target;
};
myValue.evaluateImmediate();
From @mbest comment https://github.com/knockout/knockout/issues/1019.