Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
531 views
in Technique[技术] by (71.8m points)

touch - How to remove an event listener in javascript?

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');
document.addEventListener('touchstart', function (e) {
     closePopupOnClick(e, popup);
});

but this does not actually remove the event listener. If I put the addEventListener code in a function and pass that function into the the removeEventListener it will not work bc you cannot pass params into the function. Anyone know how to do this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...