Backbone.js fire event on .remove()

2019-05-29 19:45发布

问题:

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

回答1:

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

});


回答2:

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 e.g. 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); 
}