need a knockout timer for the project

2019-02-27 23:45发布

问题:

I need a knockout timer for my project which can restart after it reaches 0 on a click. I have the following code but this wont restar. Can somebody help me.

this.countDown = ko.observable();

ko.bindingHandlers.timer = {

    update: function (element, valueAccessor) {
        var sec = $(element).text();
        var timer = setInterval(function () {

            $(element).text(--sec);
            if (sec == 0) {
                clearInterval(timer);

            }
        }, 1000);
    }
};

回答1:

If you want to use the approach from your question replace this line:

clearInterval(timer)

with something like this:

sec = 61;

See this at work:

ko.bindingHandlers.timer = {

    update: function (element, valueAccessor) {
        var sec = $(element).text();
        var timer = setInterval(function () {

            $(element).text(--sec);
            if (sec == 0) {
                sec = 61;
            }
        }, 1000);
    }
};

var vm = { countDown: ko.observable() };

ko.applyBindings(vm);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>

<div id="timer"> <span data-bind="timer: countDown">60 </span> </div>

However, I'd recommend encapsulating this kind of logic in the ViewModel, not in a custom binding. For example this kind of view model would work:

function ViewModel() {
    var self = this;
        
    self.timer = ko.observable(60);
     
    setInterval(function() {
        var newTimer = self.timer() - 1;
        self.timer(newTimer <= 0 ? 60 : newTimer);
    }, 1000);
};

ko.applyBindings(new ViewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>

<div id="timer"> <span data-bind="text: timer"></span> </div>



标签: knockout.js