Force a computed property function to run

后端 未结 5 1542
鱼传尺愫
鱼传尺愫 2021-01-30 15:29

Given a computed property

vm.checkedValueCount = ko.computed(function(){
  var observables = getCurrentValues();  //an array of ko.observable[]
  return _.filter         


        
5条回答
  •  [愿得一人]
    2021-01-30 16:04

    I realized my first answer missed your point, and won't solve your issue.

    The problem is that a computed will only reevaluate if there is some observable that forces it to re-evaluate. There is no native way to force a computed to re-evaluate.

    However, you can get around this with some hackery by creating a dummy observable value and then telling its subscribers that it has changed.

    (function() {
    
        var vm = function() {
            var $this = this;
    
            $this.dummy = ko.observable();
    
            $this.curDate = ko.computed(function() {
                $this.dummy();
                return new Date();
            });
    
            $this.recalcCurDate = function() {
                $this.dummy.notifySubscribers();
            };        
        };
    
        ko.applyBindings(new vm());
    
    }());​
    

    Here is a Fiddle showing this approach

提交回复
热议问题