[JS] 이벤트 덮어쓰기(리스너 대신 프로퍼티)

게코젤리·2023년 6월 10일
const onLoadFile = (reader) => {
  const text = document.getElementById('addPostText').value;
  const image = reader.result;
  const postData = { text, image };
  const addPostBtn = document.getElementById('addPostBtn');

  addPostBtn.onclick = () => registerPost(
    postData,
    () => {
      addPostsUI(postData);
      closeModal();
    },
    closeModal
  );
  
  switchToPostMode(image);
};

const attachListeners = (target) => {
  const uploadInput = target.querySelector('#uploadInput');
  const backBtn = target.querySelector('.add-post__backBtn');

  uploadInput.addEventListener('input', (event) =>
    openFileReader(event.target, onLoadFile, closeModal)
  );

  backBtn.addEventListener('click', () => {
    target.classList.remove(CLASSNAME_WRITE_POST);
  });
};

위와 같은 포스트 등록 동작을 구현하였는데 이미지를 로드만 한 후 뒤로가기(backBtn)를 클릭한 뒤 다시 이미지를 로드하고 등록하면 두 개의 이미지가 등록되는 문제가 생겼다.

뒤로가기 동작시 이미지 등록요소를 css로 숨김처리만 했기 때문에 input에 로드된 파일은 남아있는 탓이었다. 해결 방법은 removeEventListner, closure 등등 여러가지가 있지만 현재 코드에선 이벤트 리스너 대신 onclick 프로퍼티를 통해 직접 이벤트 핸들러 함수를 할당했다. onclick 프로퍼티는 한 번에 하나의 이벤트 핸들러만 가질 수 있기 때문에 이전의 핸들러는 자동으로 제거된다.

응? 그럼 onclick만 쓰면 될 것 같은데 왜 이벤트 리스너를 많이 쓰는 걸까?

  1. 다중 이벤트 핸들러
  2. 이벤트 캡쳐 및 버블링 제어
  3. 이벤트 핸들러를 동적으로 추가/제거

그렇단다.

addPostBtn.onclick = () => registerPost(
    postData,
    () => {
      addPostsUI(postData);
      closeModal();
    },
    closeModal
  );

0개의 댓글