Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect when a view is removed from the page using Backbone.js or Marionette.js

using Backbone.js with Marionette.js (Go Derick Bailey!). Need to detect when a view is removed from the page. Specifically, I'm overwriting it with another view.

Is there an event I can detect of function I can overload to detect when this happens?

Thanks!

like image 788
Chris Dutrow Avatar asked Jan 30 '26 18:01

Chris Dutrow


1 Answers

Marionette provides the View.onClose method for this purpose:

Backbone.Marionette.ItemView.extend({
  onClose: function(){
    // custom cleanup or closing code, here
  }
});

In vanilla Backbone you can override the View.remove method:

Backbone.View.extend({
  remove: function(){
    // custom cleanup or closing code, here

    // call the base class remove method 
    Backbone.View.prototype.remove.apply(this, arguments);
  }
});

Neither of these methods will work if you are simply clobbering the view's DOM element. If that is your case, the solution is simple: Don't do that. Remove the previous view explicitly before rendering another view in its place.

like image 132
jevakallio Avatar answered Feb 03 '26 10:02

jevakallio