删除骨干视图下的Interval

Remove Interval in Backbone view

本文关键字:Interval 视图 删除      更新时间:2023-09-26

我正在做一个非常小的时钟练习与骨干,但我不能阻止它…我试图通过返回当前间隔的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();
  })();

谢谢!

通过调用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();
}

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

相反,你需要将setInterval的结果存储在一个属性中;当你想停止它的时候可以重新使用