Manually triggered computed observables in KnockoutJS

April 3, 2015, (updated on April 21, 2015), Software Development

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.

Tweet about this on TwitterShare on FacebookEmail this to someoneShare on TumblrShare on LinkedIn

Tags: ,

Leave a Reply

Your email address will not be published. Required fields are marked *

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four 
    spaces will be stripped off, but all other whitespace
    will be preserved.
    
    Markdown is turned off in code blocks:
     [This is not a link](http://example.com)

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see http://daringfireball.net/projects/markdown/syntax