javascriptknockout.jscomputed-observable

Knoockout computed observable write doesnt update


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

self.pagesToBeDisplayed = ko.computed({
    read: function () {
       return self.pages();
    }, write: function (totalCount) {
        self.pages(totalCount) 
    },
    deferEvaluation: true
});

I am calling the above observable as self.pagesToBeDisplayed(5). However, only the value for self.pages is updated and self.pagesToBeDisplayed is still the older value.


Solution

  • It's working as expected:

    var viewmodel = function(){
      var self = this;
      self.pages = ko.observable(2);
      self.pagesToBeDisplayed = ko.computed({
        read: function () {
           return self.pages();
        }, write: function (totalCount) {
            self.pages(totalCount) 
        },
        deferEvaluation: true
      });
      
      self.update = function(){
        self.pagesToBeDisplayed(5);
      };
    };
    
    ko.applyBindings(new viewmodel());
    <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
    
    Update via input:
    <input type="number" data-bind="value: pagesToBeDisplayed">
    <br>
    
    Update via JS:
    <button data-bind="click: update">Update</button>
    
    <br><br>
    Latest values:
    <br>
    self.pages:<span data-bind="text: pages"></span>
    <br>
    self.pagesToBeDisplayed:<span data-bind="text: pagesToBeDisplayed"></span>

    It's probably some other part of your code that is causing the problem.