这个答案在概念上与@josh 给出的答案相同,但呈现为更通用的包装器。注意:此版本适用于“可写”计算。
我正在使用 Typescript,所以我首先包含了 ts.d 定义。因此,如果与您无关,请忽略第一部分。
interface KnockoutStatic
{
notifyingWritableComputed<T>(options: KnockoutComputedDefine<T>, context ?: any): KnockoutComputed<T>;
}
通知可写计算
一个可写的包装器,observable
它总是会通知订阅者——即使write
调用后没有更新任何可观察的对象
如果您不使用 Typescript ,只需替换function<T> (options: KnockoutComputedDefine<T>, context)
为。function(options, context)
ko.notifyingWritableComputed = function<T> (options: KnockoutComputedDefine<T>, 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);
}
主要用例是当您更新不会触发read
函数“访问”的可观察对象的更改时。
例如,我正在使用 LocalStorage 设置一些值,但没有任何可观察到的变化来触发重新评估。
hasUserClickedFooButton = ko.notifyingWritableComputed(
{
read: () =>
{
return LocalStorageHelper.getBoolValue('hasUserClickedFooButton');
},
write: (v) =>
{
LocalStorageHelper.setBoolValue('hasUserClickedFooButton', v);
}
});
请注意,我只需要更改ko.computed
,ko.notifyingWritableComputed
然后一切都会自行处理。
当我调用时hasUserClickedFooButton(true)
,'dummy' observable 会增加,强制任何订阅者(及其订阅者)在 LocalStorage 中的值更新时获取新值。
(注意:您可能认为notify: 'always'
扩展器是这里的一个选项 - 但这是不同的)。
对于只可读的计算 observable 有一个额外的解决方案:
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();
来自@mbest 评论https://github.com/knockout/knockout/issues/1019。