我在删除eventListener表单功能时遇到了问题。
每次调用函数都会添加一个事件,之后不会删除。
我正在检查控制台:
getEventListeners(document.querySelector('body'));
function handleKeyDown(e) {
const workoutEdit = document.querySelector('.formEdit');
const backdrop = document.querySelector('.backdrop');
if (e.key === 'Escape' && workoutEdit && backdrop) {
curWorkout.parentElement.removeChild(workoutEdit);
curWorkout.parentElement.removeChild(backdrop);
body.removeEventListener('keydown', handleKeyDown);
}
if (e.key === 'Enter') {
this.#workouts[indexWorkout].distance = +editDistance.value;
this.#workouts[indexWorkout].duration = +editDuration.value;
console.log(this.#workouts);
body.removeEventListener('keydown', handleKeyDown);
}
}
body.addEventListener('keydown', handleKeyDown.bind(this));
handleKeyDown.bind(this)
创建了一个不能被removeEventListener()
删除的新函数,如果你不把它的引用存储在某个地方
如果你需要绑定this
,你应该存储引用,像这样:
const boundHandler = handleKeyDown.bind(this);
body.addEventListener('keydown', boundHandler);
// And then under some circumstances:
body.removeEventListener('keydown', boundHandler);