Removing event listeners with anonymous function calls in JavaScript

时光总嘲笑我的痴心妄想 提交于 2019-12-08 00:10:30

问题


I'm trying to remove an event listener for created span elements where the function called is within a closure. I've tried various methods and none seem to work.

var MyClass = function () {}

MyClass.prototype.addSpan = function (el) {
    var span = document.createElement('span');
    span.innerHTML = "Text here";
    el.appendChild(span);
    span.addEventListener('click', (function (obj) { 
        return function () { 
            obj.removeSpan(); 
        }
    })(this), false);
}

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

myclass = new MyClass();

myclass.addSpan(document.getElementById('box'));

I've also used

this.removeEventListener('click', (function (obj) { 
    return function () { 
        obj.removeSpan(); 
    }
})(this), false);

in place of this.removeEventListener('click', arguments.callee, false); but had no luck.

Any help is much appreciated!


回答1:


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.




回答2:


Try changing your event handler to this.

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

        span.onclick = null;

        return function () { 
            obj.removeSpan(); 
        }
    })(this), false);


来源:https://stackoverflow.com/questions/9928754/removing-event-listeners-with-anonymous-function-calls-in-javascript

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