2013-07-04 111 views

回答

10

HTML代碼:

<span data-bind="timer: $root.countDown">120</span> 
在視圖模型

:限定countDown方法

countDown: ko.observable() 

敲除JS定義綁定:

ko.bindingHandlers.timer = { 

    update: function (element, valueAccessor) { 

     // retrieve the value from the span 
     var sec = $(element).text(); 
     var timer = setInterval(function() { 

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