设置新值时,Knockout Force 会通知订阅者可观察值

Knockout Force notify subscribers of an observable when setting new value

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

默认情况下,如果新值与旧值相同,Knockout 不会通知订阅者,因此我们需要采取一些额外的步骤来实现我们的目标。

我知道有扩展器 currentPage.extend({ notify: 'always' }) 但我只需要在特定位置使用该行为,而不是针对 observable 全局使用。

目前,我正在使用以下方法:

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