1

我的项目需要一个淘汰计时器,它可以在点击达到 0 后重新启动。我有以下代码,但这不会重新启动。有人可以帮助我。

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

1 回答 1

3

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

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 中,而不是自定义绑定中。例如,这种视图模型可以工作:

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>

于 2013-08-26T22:40:02.550 回答