How to remove an event listener in javascript?

后端 未结 1 1869
迷失自我
迷失自我 2020-12-16 01:42

I am wondering how can I remove an event listener after adding one, the way you use on and off in jquery?

document.removeEventListener(\'touchstart\');
docum         


        
相关标签:
1条回答
  • 2020-12-16 02:18

    Put the listener as a variable and attach via .addEventListener

    var myListener = function (e) {
        closePopupOnClick(e, popup);
    };
    document.addEventListener('touchstart', myListener, true);
    

    then pass it again when removing with .removeEventListener

    document.removeEventListener('touchstart', myListener);
    

    If you're not in strict mode you can make a listener remove itself with arguments.callee

    document.addEventListener('touchstart', function (e) {
        closePopupOnClick(e, popup);
        document.removeEventListener('touchstart', arguments.callee);
    }, true);
    

    If you are in strict mode, you have to use a named function expression if you want a function to remove itself

    document.addEventListener('touchstart', function myListener(e) {
        closePopupOnClick(e, popup);
        document.removeEventListener('touchstart', myListener);
    }, true);
    

    If you want to use variables in the listener that may be changed by something (e.g. a loop), then you can write a generator function, for instance

    function listenerGenerator(popup) {
        return function (e) {
            closePopupOnClick(e, popup);
        };
    }
    

    Now you can create the listener with listenerGenerator(popup) and it will scope the popup variable. Note that if popup is an Object, it will be ByRef and therefore may still be subject to changes.

    0 讨论(0)
提交回复
热议问题