Knockout js如何实现倒数计时器 [英] Knockout js how to Implement Countdown Timer

查看:74
本文介绍了Knockout js如何实现倒数计时器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Knockout js的新手。使用knockout js在html上实现倒数计时器

I'm new on Knockout js.Trying to implement countdown timer on html with using knockout js

为此,我添加了4个html元素(输入,范围和视图上的开始,停止按钮。按下开始按钮时,写入< input> 对象的值应该传递给 refreshViewModel ,然后将是倒计时过程。当倒计时处理时,剩余时间将显示在< span> 元素内。如果按下停止按钮,倒计时将停止。

For this purpose I added 4 html elements(input, span and start, stop buttons) on view. When start button is pressed, the value that written on <input> objects should be passed to refreshViewModel, and there will be countdown process. When the countdown is processing remaining time will be showed inside <span> element. If the stop button is pressed countdown will be stopped.

如果倒计时完成另一个功能(即从另一个viewModel回调),那么过滤带有一些参数的页面将是启动。

If the countdown finishes another function(that is callbacked from another viewModel) which is filtering the page with some parameters will be initiated.

将文本框值绑定到范围值。我无法弄清楚如何计算和显示内部动态的剩余价值?

Binded textbox value to span value. I cannot figure out how to count and show to remaining value inside span dynamically?

Html:

<div id="pnlTimer" class="row">
  <div class="span2 pull-right" style="border:1px solid rgb(218, 218, 218)" >
    <span style="font-weight:bold">Reload Interval</span>
    <br />
    <input  id="initialTime" style="width:20px;height:14px" data-bind="value:  initialTime" />
    <span id="remainingTime" style="visibility:hidden"> / 15</span> second(s)
    <button class="btn" style="margin-top:5px" id="StartCounter" data-bind="click: StartCounter">
       <i class="icon-play"></i>
    </button>
    <button style="visibility:hidden;margin-top:5px;margin-left:-44px" class="btn"  id="StopCounter" data-bind="click: StopCounter">
       <i class="icon-stop"></i>
    </button>
  </div>
</div>

Js:

     @Url.Content("~/Content/App/viewModels/listCasesViewModel.js
     @Url.Content("~/Content/App/viewModels/RefreshPageTimerViewModel.js                       



$(document).ready(function () {
    var viewModel = new ListCasesViewModel();
    viewModel.init();

    var pnl = $("#pnlFilterPanel").get()[0];
    ko.applyBindings(viewModel, pnl);


    var viewModelTimer = new RefreshPageTimerViewModel();
    viewModelTimer.init();

    var pnlTimer = $("#pnlTimer").get()[0];
     ko.applyBindings(viewModelTimer, pnlTimer);

    viewModelTimer.callBackMethod = viewModel.filter;


});







第一个viewModel:RefreshPageTimerViewModel:

var RefreshPageTimerViewModel = function () {
var self = this;


self.StartCounter = ko.observable();
self.StopCounter = ko.observable();
self.initialTime = ko.observable();
self.remainingTime = ko.computed(function () {
    return self.initialTime();
}, self);

countDown: ko.observable()


this.init = function () {
    self.Count();

}

this.callBackMethod = function () {
    alert("not implemented!");
}

this.Count = function () {

    var initial = self.initialTime; // initialTime value;
    var remaining = self.remainingTime; 


    if (remainingTime <= 0) {
        this.ExecuteCallBackMethod();
    }
}

this.ExecuteCallBackMethod = function () {
    this.callBackMethod();
}



};

第二个视图模型:ListCasesViewModel:

   var ListCasesViewModel = function () {
    var self = this;

self.selectedStartDate = ko.observable(null);
self.selectedEndDate = ko.observable(new Date());
self.selectedSearchKey = ko.observable("");
self.selectedStatuses = ko.observableArray();
self.selectedHospitals = ko.observableArray();

// methods...
this.init = function () {
    self.selectedEndDate(new Date());
    self.filter();
}

this.filter = function () {

    // get filter control values
    var startDate = self.selectedStartDate(); // dtStart.value();
    var endDate = self.selectedEndDate(); //dtEnd.value();
    var searchText = self.selectedSearchKey();

    //And Some calculations....


推荐答案

主要问题是你的ViewModel代码,它使用 observable 你想要一个函数(启动和停止计数器)。此外,它似乎没有明确定义它想要做什么。

The main problem is your ViewModel code, it uses an observable where you wanted a function (to Start and Stop the counter). Also, it does not seem to have a clear definition of what it is trying to do.

此外,我假设您希望开始按钮显示何时停止计时器,以及显示定时器启动时间的停止按钮 - 所以我也可以自由添加此功能。

Also, im assuming you wanted the Start button to show when the timer is stopped, and the Stop button to show when the timer is started - so ive taken the liberty to add this functionality too.

这是重写的视图模型:

var RefreshPageTimerViewModel = function () {
    var self = this;

    self.timerId = 0;
    self.elapsedTime = ko.observable(0);
    self.initialTime = ko.observable(0);
    self.remainingTime = ko.computed(function(){
        return self.initialTime() - self.elapsedTime();
    });
    self.isRunning = ko.observable(false);

    self.StartCounter = function(){
        self.elapsedTime(0);
        self.isRunning(true);
        self.timerId = window.setInterval(function(){
            self.elapsedTime(self.elapsedTime()+1);
            if(self.remainingTime() == 0){
                clearInterval(self.timerId);
                self.isRunning(false);
                self.Callback();
            }
        },1000)
    }
    self.StopCounter = function(){
        clearInterval(self.timerId);
        self.isRunning(false);
    }
    self.Callback = function(){}
}

有几点需要注意:


  • 有一个属性 timerId ,这不需要是可观察的,但允许我们停止用于递增 elapsedTime的计时器

  • Has a property timerId, which does not need to be observable, but allows us to stop the timer which is used to increment the elapsedTime

有一个可观察的属性 isRunning 用于控制开始和停止按钮的可见性

has an observable property isRunning used to control the visibility of the Start and Stop buttons

有一个空函数 Callback ,当倒计时到零时,它可用于执行任何函数。

has an empty function Callback which can be used to execute any function when the countdown reaches zero.

以下是新标记:

<div id="pnlTimer" class="row">
  <div class="span2 pull-right" style="border:1px solid rgb(218, 218, 218)" >
    <span style="font-weight:bold">Reload Interval</span>
    <br />
    <input  id="initialTime" style="width:20px;height:14px" data-bind="value:  initialTime" />
    <span id="remainingTime" data-bind="text: remainingTime"></span> second(s)
    <button class="btn" style="margin-top:5px" id="StartCounter" data-bind="click: StartCounter, visible: !isRunning()">
       start
    </button>
    <button style="margin-top:5px" class="btn"  id="StopCounter" data-bind="click: StopCounter, visible:isRunning()">
       Stop 
    </button>
  </div>
</div>

注意添加可见:!isRunning()到开头, visible:isRunning()到停止按钮。

Note the addition of visible: !isRunning() to the start and visible:isRunning() to the stop buttons.

最后,这是初始代码:

$(function(){
     var viewModelTimer = new RefreshPageTimerViewModel();
    viewModelTimer.Callback = function(){
        alert("finished");
    };
    ko.applyBindings(viewModelTimer);
})

注意创建一个只提醒的回调函数。您的代码可以是原样,即 viewModelTimer.callBackMethod = viewModel.filter;

Note the creation of a callback function which simply alerts. Your code could be as it was, ie viewModelTimer.callBackMethod = viewModel.filter;

最后,一个实例允许你玩游戏: http://jsfiddle.net/eF5Ec/

Finally, a live example to allow you to play around: http://jsfiddle.net/eF5Ec/

这篇关于Knockout js如何实现倒数计时器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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