subZero
subZero

Reputation: 5176

Dynamically unbind eventListeners (garbage collection)

I have the following code that binds eventListeners:

// this code is part of a larger object
_boundEventsTracker: [],
_$bindEvents: function(){
    var self = this;
    this.actions.forEach(function(acs){
        acs = acs.split(' ');
        var find = document.querySelector(acs[1]);
        if(find!=null){
            // make sure we only bind events once
            if(self._boundEventsTracker.indexOf(acs[1]) == -1){
                find.addEventListener(acs[0], function(e){
                    self.functions[acs[2]].call(self, e);
                });
                self._boundEventsTracker.push(acs[1]);
            }
        } else {
            /* could not bind
            this is usually because the element resides on a partial page */
        }
    });
    console.log("Events:");
    console.log(this._boundEventsTracker.length);
},

this.actions may look like this, for example:

actions: [
    'click .settings toggleSidebar',
],

On hashchange, I dynamically load a page and then call the _$bindEvents method (_$load is a promise based wrapper for XMLHttpRequest):

window.addEventListener('hashchange', function(e){
    self._$load(e).then(function(content){
         document.querySelector('.pageArea').innerHTML=content; // <- populate here
         self._$bindEvents();
    }});

This gives the following advantage: whenever the hashbang changes, a new view is loaded, html is polled into the main view and then events are bound to elements that resides in that particular partial view.

1 Is it necessary to unbind eventListeners when the view is later destroyed (clean up)?

2 Are there any performance issues with having loaded many eventListeners into memory?

Upvotes: 1

Views: 114

Answers (1)

David Hellsing
David Hellsing

Reputation: 108500

  1. no, the garbage collector removes event listeners for nodes that has been removed from the DOM. Some older versions of IE has memory leaks, but it shouldn’t be an issue anymore.

  2. maybe, but probably not. It depends on how many listeners you have, the complexity of DOM structures, event delegations etc. It’s impossible to give a generic answer to that question. If any, the issues will be noticable in the UI, not in memory consumption.

If you are developing an SPA, consider delegating events to the top as they will become much more managable than binding/rebinding all of them on each hashchange.

Also, using a custom event abstraction like this might be an issue for future co-workers or collaborators to understand.

Upvotes: 2

Related Questions