Question

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.

Was it helpful?

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);
    }
};
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top