Removing Event Listeners within Event Handlers
You're seeking a solution to remove an event listener from within its own definition. However, due to JavaScript's event handling mechanism, this is not directly feasible.
One approach is to employ named functions. By creating a named function and using it as the event handler, you can later remove the event listener by referencing its function name. Simultaneously, the click variable should be declared outside the event handler to facilitate its increment.
var click_count = 0; function myClick(event) { click_count++; if(click_count == 50) { canvas.removeEventListener('click', myClick); } } canvas.addEventListener('click', myClick);
Alternatively, you can utilize closure to create a function that encapsulates the click_count variable. This approach enables you to increment the counter across multiple elements.
var myClick = (function( click_count ) { var handler = function(event) { click_count++; if(click_count == 50) { canvas.removeEventListener('click', handler); } }; return handler; })( 0 ); canvas.addEventListener('click', myClick);
Lastly, if you prefer each element to have its own counter, consider employing an anonymous function that accepts a parameter for its initial click count.
var myClick = function( click_count ) { var handler = function(event) { click_count++; if(click_count == 50) { canvas.removeEventListener('click', handler); } }; return handler; }; canvas.addEventListener('click', myClick( 0 ));
The above is the detailed content of How Can I Remove an Event Listener from Within Its Own Event Handler in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!