knockout.jscustom-binding

Knockout js countdown timer


I've been looking for a sample to create a custom countdown timer binding for knockout js!

I found this question jQuery countdown timer and adapt it for Knockout Js.


Solution

  • html code:

    <span data-bind="timer: $root.countDown">120</span>
    

    in the viewModel: define countDown

    countDown: ko.observable()
    

    knockout js custom binding:

    ko.bindingHandlers.timer = {
    
        update: function (element, valueAccessor) {
    
            // retrieve the value from the span
            var sec = $(element).text();
            var timer = setInterval(function() { 
    
                $(element).text(--sec);
                if (sec == 0) {
                    clearInterval(timer);
                }
            }, 1000);
        }
    };