JavaScript:删除事件监听器

我正在尝试删除侦听器定义中的事件侦听器:

I'm trying to remove an event listener inside of a listener definition:

canvas.addEventListener('click', function(event) {
    click++;
    if(click == 50) {
        // remove this event listener here!
    }
// More code here ...

我怎么能这样做?这 = 事件...

How could I do that? this = event...

推荐答案

你需要使用命名函数.

另外,click 变量需要在处理程序之外才能递增.

Also, the click variable needs to be outside the handler to increment.

var click_count = 0;

function myClick(event) {
    click_count++;
    if(click_count == 50) {
       // to remove
       canvas.removeEventListener('click', myClick);
    }
}

// to add
canvas.addEventListener('click', myClick);

<小时>

您可以像这样关闭 click_counter 变量:


You could close around the click_counter variable like this:

var myClick = (function( click_count ) {
    var handler = function(event) {
        click_count++;
        if(click_count == 50) {
           // to remove
           canvas.removeEventListener('click', handler);
        }
    };
    return handler;
})( 0 );

// to add
canvas.addEventListener('click', myClick);

通过这种方式,您可以跨多个元素递增计数器.

This way you can increment the counter across several elements.

如果您不希望这样,并且希望每个人都有自己的计数器,那么请执行以下操作:

If you don't want that, and want each one to have its own counter, then do this:

var myClick = function( click_count ) {
    var handler = function(event) {
        click_count++;
        if(click_count == 50) {
           // to remove
           canvas.removeEventListener('click', handler);
        }
    };
    return handler;
};

// to add
canvas.addEventListener('click', myClick( 0 ));

我忘记命名在最后两个版本中返回的处理程序.已修复.

相关文章