Rico Suter's blog.
 


In KnockoutJS I sometimes need to create a computed observable which does not automatically detect the dependencies and which has to be triggered manually. This may be required if the computation is very complex and should only run in certain situations.

To implement this special type of computable, extend the ko object with a new manualComputed method:

ko.manualComputed = function (func) {
    var changes = 0;
    var dummy = ko.observable();
    function observable() {
        dummy();
        var temp = ko.computed(func);
        var result = temp.peek();
        temp.dispose();
        return result;
    }
    ko.subscribable.call(observable);
    observable.update = function () { dummy(++changes); };
    ko.utils.extend(observable, ko.observable["fn"]);
    return observable;
};    

After implementing the manualComputed method, you can create manually triggered computed observables this way:

...
this.c = ko.manualComputed(function () {
    return a() + b(); // TODO: Add your logic here
});

To trigger a reevaluation, simply invoke the update method:

this.c.update();

The function of the computable c is now only executed when the update method is called or when the data binding is set up.



Discussion