Memory Management in JS Web Apps
1 min read

Memory Management in JS Web Apps

Memory management is a fairly crucial part to building JavaScript web applications, and just because the language has a garbage collector it doesn't absolve you from all duties.

Take your classic controller (or view in Backbone land). In its constructor it may bind to some model events, perhaps re-rendering itself when a record changes. You'll need to clean up these events listeners at some stage, especially if you're constantly instantiating and removing the controller.

Backbone and Spine have a 'remove' method which, behind the scenes, will remove the controller from the DOM via jQuery. Backbone will even cleanup any event handlers using it's Event.fn.listenTo feature. However, calling this manually whenever we want to remove a controller is a bit onerous, and means we can't use features like jQuery.fn.html() to remove controllers. We somehow need to detect when the controller's element is removed from the DOM.

It turns out that jQuery already has a form of this event listener cleanup, $.cleanData(). Whenever an element is removed from DOM, such as by replacing its parent's HTML, it's passed through this function to strip jQuery's event handlers.

We can tap into this existing feature to fire our own remove event whenever a element is removed from the DOM. We can then listen to this event in our controller and do any cleaning up required.

Rather than override $.cleanData(), we can just define our own special event:

jQuery.event.special.remove = {
  remove: function(e) { 
    if (e.handler) e.handler(); 
  }
};

Here we've defined an event named remove which, when processed by $.cleanData(), will be triggered.

The last step is to bind to this event in our controller:

var Controller = function () {
  this.$el = $('<div />');
  this.$el.on('remove', this.release);
};

Controller.prototype.release = function () {
  // Cleanup data
  // this.model.off('change', this.render);
};

That's all there is to it! Now whenever the controller's element is removed from the DOM, release will invoked and our event listeners cleaned up.


This is an article in the ongoing series about Monocle.

Enjoying these posts? Subscribe for more