在Backbone视图中删除Interval

时间:2012-12-20 22:03:04

标签: javascript backbone.js

我正在为Backbone练习做一个非常小的时钟,但是我无法阻止它。我试图通过返回当前间隔的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();
  })();

谢谢!

2 个答案:

答案 0 :(得分: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();
}

答案 1 :(得分:0)

每次调用updateWatch时,都会重新创建“Interval”对象。

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