Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 226
Anas Avatar asked Jul 04 '13 14:07

Anas


1 Answers

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);
    }
};
like image 93
Anas Avatar answered Dec 06 '22 04:12

Anas