简体   繁体   中英

How to remove event listener if the attached function is a closure?

example:

for (var i = 0 ; i < a.length ; i ++) {
    a[i].addEventListener("touchend", f(i));
}

function f(param) {
    return function() {
        for (var i = 0 ; i < a.length ; i ++) {
            a[i].removeEventListener("touchend", f(i));
        }
    }
}

It just doesn't work,what should I do?

In order to call .removeEventListener() you have to retain a reference to the function. That means you will have to give the function an identifier that you can then use in both .addEventListener() and .removeEventListener() . The symbol can be a local symbol (it doesn't have to be global), but you will need a symbol in order to be able to use it both places.

If you can explain a little more about what you're trying to accomplish with the code you show and where you'd want to use .removeEventListener() , we can probably offer a more concrete suggestion on how to change it (I don't follow what you're trying to do with it).

Perhaps something like this:

var temp;
for (var i = 0 ; i < a.length ; i ++) {
    temp = f(i);
    a[i].touchEndHandler = temp;
    a[i].addEventListener("touchend", temp);
}

Then, sometime later, you could do:

x.removeEventListener("touchend", x.touchEndHandler);

Or, depending upon where your .removeEventListener() code is, you might be able to save the function reference in a closure variable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM