✔ 인스타그램 메인페이지 클론 프로젝트중, 도은님의 도움으로 오늘 알게된
removeEventListener
에 대해 정리해보고자 한다.
target.removeEventListener(type, listener[, options]); target.removeEventListener(type, listener[, useCapture]); // const target = document.querySelector('.button'); const hellog = () => console.log(hello); target.addEventListener('click', hello) // 이벤트 작동 target.removeEventListener('click', hello) // 이벤트 중지
target의 기존에 등록했던 이벤트 리스너를 제거하는 함수
등록된 이벤트 리스너를 제거함으로써, 콜백 함수의의 동작 방지
type
: 이벤트 리스너를 등록할 DOM 노드
listener
: 이벤트가 발생했을 때 처리를 담당하는 콜백함수 참조
useCapture
: 이벤트 단계, 캡처링/버블링(default)단계 설정 가능(이 부분에 대해서는 아직 이해가 안가간다.. 찾아보도록 해야겠다.)
수정 전
if (commentValue.length > 0) { commentUploadButton.classList.add('active'); commentUploadButton.disabled = false; commentUploadButton.addEventListener('click', leaveComment); comment.addEventListener('keydown', pressEnter); } if (commentValue.length === 0) { commentUploadButton.classList.remove('active'); commentUploadButton.disabled = true; }
수정 후
if (commentValue.length > 0) { commentUploadButton.classList.add('active'); commentUploadButton.disabled = false; commentUploadButton.addEventListener('click', leaveComment); comment.addEventListener('keydown', pressEnter); } if (commentValue.length === 0) { commentUploadButton.classList.remove('active'); commentUploadButton.disabled = true; commentUploadButton.removeEventListener('click', leaveComment); // 추가 comment.removeEventListener('keydown', pressEnter); // 추가 }
commentValue.length === 0
일때, click
과 active
이벤트에 remove를 적용하지 않아 생겼던 문제였다. 즉, input
창이 공백이었을때도 앞선 if
문 이후, commentUploadButton
과 comment
의 이벤트가 제거가 되지 않았기에 버그가 발생했던 것이다. (입력된 글자가 없음에도 불구하고 공백이 계속 댓글이 달렸다.) 결론은 비활성화 로직에 대한 생각을 꼭! 하도록 하자.
저도 덕분에 배웠어요~~~!~!👍🏻👍🏻