addEventListener를 사용한다면 removeEventListener를 통해 지워주지 않으면 메모리 누수가 발생할 수 있다.
원하는 시점에 이벤트를 지우기 위해 this.todoInput 변수를 만들었다.
그리고 HTML 요소를 변수에 담아줬는데 동작이 안 된다.
에러 문구
Uncaught TypeError: EventTarget.removeEventListener: At least 2 arguments required, but only 1 passed
작성한 코드
// 생략
addInputHandler = () => {
if (this.todoInput) {
const text = this.todoInput.value.trim();
this.todoInput.removeEventListener('input');
this.todoInput.remove();
this.addButton.textContent = 'ADD';
if (text) {
this.todoService.addTodo(text);
}
this.renderTodos();
} else {
this.showInput();
}
}
showInput = () => {
this.addButton.textContent = 'SAVE';
this.todoInput = document.createElement('input');
this.todoInput.type = 'text';
this.todoInput.placeholder = '할 일 입력';
this.todoInput.classList.add('todo-input');
this.addButton.parentNode.insertBefore(this.todoInput, this.addButton);
todoInput.focus();
const handleKeydown = (e) => {
if (e.key === 'Enter') {
this.addInputHandler();
} else if (e.key === 'Escape') {
this.todoInput.remove();
this.addButton.textContent = 'ADD';
}
};
todoInput.addEventListener('keydown', handleKeydown)
}
// 생략
removeEventListener에 매개변수가 두 개가 들어가야 하는데 'input' 하나만 있어서 발생한 문제였다.
메소드 흐름상 showInput에 있는 handleKyedown 함수를 전달할 방법을 생각하다가 보니 굳이 보낼 필요가 없었다.
this.todoInput을 없애고 메소드별로 변수를 생성해서 원하는 동작을 할 수 있게 다시 수정했다.
수정된 코드
// 생략
addInputHandler = () => {
const todoInput = document.querySelector('.todo-input');
if (todoInput) {
const text = todoInput.value.trim();
todoInput.remove();
this.addButton.textContent = 'ADD';
if (text) {
this.todoService.addTodo(text);
}
this.renderTodos();
} else {
this.showInput();
}
}
showInput = () => {
this.addButton.textContent = 'SAVE';
const todoInput = document.createElement('input');
todoInput.type = 'text';
todoInput.placeholder = '할 일 입력';
todoInput.classList.add('todo-input');
this.addButton.parentNode.insertBefore(todoInput, this.addButton);
todoInput.focus();
const handleKeydown = (e) => {
if (e.key === 'Enter') {
todoInput.removeEventListener('input', handleKeydown);
this.addInputHandler();
} else if (e.key === 'Escape') {
todoInput.remove();
this.addButton.textContent = 'ADD';
}
};
todoInput.addEventListener('keydown', handleKeydown)
}
// 생략
이렇게 수정하니 removeEventListener를 추가할 수 있었고, 정상동작하는 것 까지 확인했다.
끝!
'공부합시다 > Javascript' 카테고리의 다른 글
비트연산 (1) | 2025.03.27 |
---|---|
배열 순서 바꾸기 (0) | 2025.03.19 |
[개념 정리] 얕은 복사(Shallow Copy)&깊은 복사(Deep Copy) (1) | 2025.03.12 |
JavaScript에서 시간 다루기 (1) | 2024.09.05 |
[TypeScript] 속성이 'Window & typeof globalThis' 형식에 없습니다. ts(2551) (0) | 2024.02.15 |