2012-12-20 40 views
0

我正在为骨干练习做一个非常小的时钟,但我无法阻止它..我试图通过返回当前间隔的ID来阻止它,但它不会没有工作。我做错了什么?在主干视图中删除间隔

var app = { 
    lap: Backbone.Model.extend({ 
    defaults: { 
     time: 0 
    } 
    }), 
    views: { 
     home: Backbone.View.extend({ 
     el: $('#the-clock'), 
     tagName: 'div', 
     events: { 
      "click #save-lap" : "stopWatch" 
     }, 
     render: function(){ 
     var time = this.theWatch(), 
      tpl = '<button id="save-lap"></button><span id="clock">Son las <%= time %></span>'; 

     $(this.el).html(_.template(tpl,time)); 
     }, 
     theWatch: function(){ 
      var currentTime = new Date(), 
       currentHour = currentTime.getHours(), 
       currentMinutes = currentTime.getMinutes(), 
       currentSeconds = currentTime.getSeconds(), 
       timeOfDay = (currentHour < 12) ? "AM":"PM"; 

      return data = { 
       time: currentHour + ':' + currentMinutes + ':' + currentSeconds + ' ' + timeOfDay 
      } 
     }, 
     updateWatch: function(){ 
      return setInterval(
       function(){ 
        this.render(); 
       }.bind(this), 
       1000 
     ) 
     }, 
     stopWatch: function(){ 
      console.log('stop') 
      var clock = this.updateWatch(); 
      clearInterval(clock); 
     }, 
     initialize: function(){ 
      this.render(); 
      this.updateWatch(); 
     } 
    }) 
}, 
ini: function(){ 
    var Home = new this.views.home(); 
} 
}; 

(function(){ 
    app.ini(); 
    })(); 

谢谢!

回答

3

通过调用this.updateWatch(),您每次要停止时都会创建一个新的时间间隔!试试这个:

updateWatch: function(){ 
    return setInterval(
     function(){ 
      this.render(); 
     }.bind(this), 
     1000 
    ) 
}, 
stopWatch: function(){ 
    clearInterval(this.clockInterval); 
}, 
initialize: function(){ 
    this.render(); 
    this.clockInterval = this.updateWatch(); 
} 
0

您每次调用updateWatch时都会重新创建'Interval'对象。

相反,您需要将setInterval的结果存储在属性中;并在你想停止它时重新使用它。