In JavaScript, removing an event listener within the same event handler's definition can pose challenges. To address this, consider the following strategies:
One approach involves using named functions:
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);
Alternatively, you can close over the click counter using an indirect event handling pattern:
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);
If you need each element to have its own counter, you can use a function generator:
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));
The above is the detailed content of How Can I Safely Remove JavaScript Event Listeners Inside Their Own Handlers?. For more information, please follow other related articles on the PHP Chinese website!