javascriptknockout.jscomputed-observablemodular-design

Knoockout computed observable doesnt update


The following is a computed observable, and i am calling its write function, but the write doesnt update the value for the computed.

self.pagesToBeDisplayed = ko.computed({
    read: function () {

       var value = otherFile.PerformWork();
       return self.pages(value);
    }, write: function (totalCount) {
        var value = otherFile.PerformWork(totalCount);
        self.pages();
        self.pages(value) 
    },
    deferEvaluation: true
});

otherFile.PerformWork() is a function in other javascript file thta just updates self.pages().

However, the value for self.pages and self.pagesToBeDisplayed is still the older value. it doesnt get updated after the otherFile.PerformWork(totalCount);


Solution

  • Your read function is currently writing to the pages observable instead of reading from it. To read, call the observable with no arguments: self.pages(). To write, call with one argument: self.pages(value).

    Your write function should be writing to the observable, and your read function should only be reading.