Knockout Force在设置新值时通知订阅者一个observable

Ale*_*mov 3 javascript knockout.js

假设我们想要为一个observable分配一个新值,并通知订阅者,无论新值是否等于旧值.

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

但看起来它可能会更好.

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

Max*_*din 11

您的方法已经足够好了,除非您可能想重构它以便在值发生变化时不通知订阅者两次.

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();       
}
Run Code Online (Sandbox Code Playgroud)

在您的情况下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);
Run Code Online (Sandbox Code Playgroud)