Backbone.js在.remove()上触发事件

时间:2012-03-01 08:52:54

标签: backbone.js intervals

我需要在删除Backbone.js视图时触发一个函数。我想有点像去构造函数。下面的代码是我写的代码片段;我知道它不会起作用。但是,我确实记得在过去看过如何编写执行此操作的函数的视频教程。我需要运行解构函数的原因是在删除视图时清除视图中设置的间隔。

ViewWeather = Backbone.View.extend({
      interval: setInterval(function() {console.log('interval fire');}, 1000),

      // made up function
      deconstructor: function () {
            // if the view is removed
            clearInterval(this.interval);

     }
});

var viewweather = new ViewWeather();

2 个答案:

答案 0 :(得分:8)

这篇博文应该会为您提供更好的信息

http://lostechies.com/derickbailey/2011/09/15/zombies-run-managing-page-transitions-in-backbone-apps/

最值得注意的部分

Backbone.View.prototype.close = function(){
  this.remove();
  this.unbind();
  if (this.onClose){
    this.onClose();
  }
}

然后

MyView = Backbone.View.extend({
  initialize: function(){
    this.model.bind("change", this.render, this);
  },
  render: function(){ ... },

  onClose: function(){
    this.model.unbind("change", this.render);
  }

});

答案 1 :(得分:4)

我不确定我是否理解正确,但您展示的方法似乎是正确的:

dispose: function(id) {
    clearInterval(this.interval);
    this.remove();
}

你将不得不自己打电话,例如一个事件:

initialize: function(opts) {
    router.bind('route:leave', this.dispose, this); 
},

评论后编辑:这应该可以重载remove

remove: function() { 
    clearInterval(this.interval);
    Backbone.View.prototype.remove.call(this); 
}  
相关问题