[removed] remove event listener

后端 未结 8 1434
面向向阳花
面向向阳花 2020-11-22 04:58

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

canvas.addEventListener(\'click\', function(event) {
    click++;
    if(click == 50         


        
8条回答
  •  南方客
    南方客 (楼主)
    2020-11-22 05:36

    You need to use named functions.

    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);
    

    EDIT: 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 ));
    

    EDIT: I had forgotten to name the handler being returned in the last two versions. Fixed.

提交回复
热议问题