1

What's the best way of unbinding event handlers in the destroy method of a plain JS plugin? The following (non working) code shall demonstrate what I mean:

var myPlugin = (function(){
    function myPlugin(selector){
        var elems = document.querySelectorAll(selector);

        for (var i=0; i<elems.length; i++) {
            function _handler(){ console.log('Hello'); }
            elems[i].addEventListener("click", _handler);
        }

        this.destroy = function(){
            document.removeEventListener("click", _handler);
        };
    }
    return myPlugin;
})();

So, I iterate over a set of elements and do something with them, including attaching an event handler function. The problem: In plain JS, I need a reference to the original handler in order to remove it when the plugin instance gets destroyed.

This snippet naturally cannot work, because the event handler function is written over and over again with each selected element.

One way of handling this: Creating functions with a dynamic/unique name, as described here: Creating functions dynamically in JS. The function needs to be globally set on the window object. Then, I just need to remember the name (e.g. by using a data attribute on the selected element) and with that, it's possible to unbind the event later on.

However, this approach is clumsy and I run into issues on IE8, when using such function with attachEvent. Is there a better way or any best practice for that?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Simon Steinberger
  • 6,605
  • 5
  • 55
  • 97

0 Answers0