英文:
Unable to remove eventListener with removeEventListener
问题
I got problem with removing eventListener form function.
每次调用函数都会添加另一个事件,之后不会被移除。
我在控制台中使用以下代码进行检查:
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));
英文:
I got problem with removing eventListener form function.
Every call a function is adding another event and after that is not removed.
Im checking in console with:
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));
答案1
得分: 2
handleKeyDown.bind(this)
创建了一个新的函数,如果你不在某处存储对它的引用,它将无法通过removeEventListener()
来移除。
如果需要绑定this
,你应该像这样存储引用:
const boundHandler = handleKeyDown.bind(this);
body.addEventListener('keydown', boundHandler);
// 然后在某些情况下:
body.removeEventListener('keydown', boundHandler);
英文:
handleKeyDown.bind(this)
creates a new function that can't be removed by removeEventListener()
if you don't store the reference to it somewhere.
If you need to bind this
, you should store the reference, like this:
const boundHandler = handleKeyDown.bind(this);
body.addEventListener('keydown', boundHandler);
// And then under some circumstances:
body.removeEventListener('keydown', boundHandler);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论