需要一个项目的淘汰赛计时器 [英] need a knockout timer for the project

查看:109
本文介绍了需要一个项目的淘汰赛计时器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个项目的淘汰赛计时器,该计时器可以在单击一次达到0后重新启动.我有以下代码,但不会重演.有人可以帮我吗.

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);
    }
};

推荐答案

如果您要使用问题中的方法,请替换此行:

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

clearInterval(timer)

具有这样的内容:

sec = 61;

在工作中看到这个:

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>

但是,我建议将这种逻辑封装在ViewModel中,而不是在自定义绑定中.例如,这种视图模型可以工作:

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>

这篇关于需要一个项目的淘汰赛计时器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆