Backbone.js fire event on .remove()

一曲冷凌霜 提交于 2019-12-13 12:35:38

问题


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


来源:https://stackoverflow.com/questions/9513194/backbone-js-fire-event-on-remove

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!