need a knockout timer for the project

后端 未结 1 1794
北海茫月
北海茫月 2021-01-23 14:14

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.

th         


        
相关标签:
1条回答
  • 2021-01-23 14:43

    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>

    0 讨论(0)
提交回复
热议问题