Knockout js countdown timer
Asked Answered
S

1

6

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.

Sulphuric answered 4/7, 2013 at 14:57 Comment(0)
S
11

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);
    }
};
Sulphuric answered 4/7, 2013 at 14:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.