Backbone.js fire event on .remove()

I need to fire a function when a Backbone.js view is removed. I guess something like a de-constructor. The code below is a snippet I wrote; I know it won't work. However, I do remember seeing in the past a video tutorial on how to write a function that does this. The reason I need to run a de-constructing function is to clear the interval set inside a view when the view is removed.

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();

This blog post should give you some better info

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

most notable parts

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

and then

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

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

});

i am not sure if I understand you correctly, but the approach you are showing seems correct:

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

you are going to have to call dispose yourself, by eg an event:

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

edit after comments: this should work to overload remove

remove: function() { 
    clearInterval(this.interval);
    Backbone.View.prototype.remove.call(this); 
}  
链接地址: http://www.djcxy.com/p/63094.html

上一篇: Backbone JS:可以在其他视图中触发更新吗?

下一篇: Backbone.js在.remove()上触发事件