假设我们要为可观察对象分配一个新值,并通知订户,无论新值是否等于旧值。
默认情况下,如果新值与旧值相同,Knockout不会通知订阅者,因此我们需要采取一些额外的步骤来实现我们的目标。
我知道有扩展器,currentPage.extend({ notify: 'always' })
但是我只需要在特定位置使用该行为,而无需在全局范围内观察即可。
当前,我正在使用以下方法:
// Some view model property of primitive type
self.currentPage = ko.observable(1);
// Some view model method
self.foo = function (newPage) {
var currentPageObservable = self.currentPage;
// Save the old value
var oldCurrentPageValue = currentPageObservable();
// Update the observable with a new value
currentPageObservable(newPage);
if(oldCurrentPageValue === newPage) {
// If old and new values are the same - notify subscribers manually
currentPageObservable.valueHasMutated();
}
};
但这看起来可能会更好。
例如,为什么淘汰赛只是不提供一种始终向订户通知可观察对象的新值分配方法?还是我想念这样的人?
您完成相同任务的方法是什么?
您的方法足够好,只是您可能要重构它,以便在值更改时不会两次通知订户。
if (oldCurrentPageValue !== newPage) {
// Update the observable with a new value
currentPageObservable(newPage);
}
else {
// If old and new values are the same - notify subscribers manually
currentPageObservable.valueHasMutated();
}
在您的情况下currentPageObservable(newPage)
通知订户,此后valueHasMutated
将第二次通知订户。
另一种方法将扩展ko.observable
为特定方法
ko.myObservable = function Observable(initialValue) {
var result = ko.observable(initialValue);
result.updateWithNotification = function (newValue) {
...
}
return result;
}
var o = ko.myObservable();
o.updateWithNotification(newValue);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句