Knockout Force在设置新值时通知订阅者可观察到的值

Knockout Force notify subscribers of an observable when setting new value

本文关键字:观察 Force 设置 新值时 通知 Knockout      更新时间:2023-09-26

假设我们想给一个可观察对象分配一个新值,并通知订阅者,无论新值是否等于旧值。

默认情况下,如果新值与旧值相同,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();
        }
    };

但这看起来可能会更好。

例如,为什么Knockout没有提供一种为始终通知订阅者的可观察对象分配新值的方法还是我错过了这样一个
你有什么方法来完成同样的任务

您的方法已经足够好了,只是您可能需要对其进行重构,以便在值发生更改时不会两次通知订阅者。

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);