Search code examples
knockout.jscustom-binding

Knockout custom binding get value before update


I have a custom binding, that has implemented update.

I would like to know what the value was before update was called. I can not see that it is passed into any of the parameters. Have i missed it?

    ko.bindingHandlers.ticker= {
        update: function (element, valueAccessor, allBindingsAccessor) {
            var toNumber = ko.utils.unwrapObservable(valueAccessor());
            var fromNumber = 0; //<---- can i set this to the old value?

            var counter = new Ticker(element, fromNumber, toNumber);

            counter.start();
        }
    }

Currently i am counting from 0 to the value (this is simply animated in the UI) but i would like to be able to count from the old value to the new value instead of it resetting to 0 and then counting from there.


Solution

  • There are two ways to do this:

    1) Use ko.utils.domData API to store some data with your element.

    // Read previous data
    var prevData = ko.utils.domData.get(element, 'dataKey');
    var newData = 42;
    
    // Remember data for next time update is called
    ko.utils.domData.set(element, 'dataKey', newData);
    

    2) Do not use update at all. Everything you do with update you can also do with a computed or a simple subscription.

    ko.bindingHandlers.ticker = {
        init: function (element, valueAccessor, allBindingsAccessor) {
            var toNumber = ko.utils.unwrapObservable(valueAccessor());
            var fromNumber = 0;        
    
            function startTicker(toNumber) {
                var counter = new Ticker(element, fromNumber, toNumber);
                counter.start();
                fromNumber = toNumber;
            }
    
            ko.computed(function () {
                startTicker(toNumber);
            }, null, { disposeWhenNodeIsRemoved: element });
        }
    }
    

    Note the computed will be safely disposed if your dom node is removed.