Removing event listeners with anonymous function calls in JavaScript

梦想的初衷 提交于 2019-12-06 12:54:38
var MyClass = function () {}
MyClass.prototype.listener=null;
MyClass.prototype.addSpan = function (el) {
    var span = document.createElement('span');
    span.innerHTML = "Text here";
    el.appendChild(span);
    span.addEventListener('click', (function (obj) { 
        return obj.listener = function () { 
            obj.removeSpan(this); // here 'this' refers to 'span'
        }
    })(this), false);
}

MyClass.prototype.removeSpan = function (el) {
    alert('removing span');
    el.removeEventListener('click', this.listener, false);
    // .... remove span .... 
}

myclass = new MyClass();
myclass.addSpan(document.getElementById('box'));

Without a reference of the listener you can't remove it, so I've also added a property (listener) to the MyClass' prototype and then returned the reference as return obj.listener and also you need to pass the object as I've passed it obj.removeSpan(this); and in the removeSpan I've received with el so I could've done el.removeEventListener, hope it helps.

You can also do this

var MyClass = function () {this.listener=null;}

instead of

MyClass.prototype.listener=null;

Here is an example.

Try changing your event handler to this.

span.addEventListener('click', (function (obj) { 

        span.onclick = null;

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