중복 호출이나 상태 업데이트가 겹치면서 발생하는 현상

해당 문제의 구간

/* 더미 댓글 */
const COMMENTS = [
  { writer: "김민준", date: "2026-09-05 14:20", text: "리뉴얼 축하드려요! 정말 깔끔하고 보기 좋네요 👍" },
  { writer: "이서연", date: "2026-09-05 15:02", text: "모바일에서도 훨씬 편해진 것 같습니다. 좋은 소식 감사합니다." },
];
// 댓글 등록
  $("#commentForm").addEventListener("submit", (e) => {
    e.preventDefault();
    const text = $("#commentInput").value.trim();
    if (!text) return;
    state.comments.push({ writer: "방문자", date: TODAY + " (방금)", text });
    $("#commentInput").value = "";
    renderComments();
    showToast("댓글이 등록되었습니다.");
  });
}

문제 현상(Issue)

댓글 2개 생성, 작성자 댓글 상단 고정에 대한 문제로 이벤트 리스너의 중복 바인딩이 2번 등록되어 해당 문제를 야기함

원인 분석(Root Cause)

해결 방법

이벤트 중복 등록을 원천 차단하고, 작성자 댓글은 상단에 고정되도록 정렬하는 수정 코드입니다.

// 1. 더미 데이터에 고유 id와 작성자/고정 플래그 추가
const COMMENTS = [
  { id: 1, writer: "김민준", date: "2026-09-05 14:20", text: "리뉴얼 축하드려요! 정말 깔끔하고 보기 좋네요 👍", isAuthor: false },
  { id: 2, writer: "이서연", date: "2026-09-05 15:02", text: "모바일에서도 훨씬 편해진 것 같습니다. 좋은 소식 감사합니다.", isAuthor: false },
];

// 2. 렌더링 함수: 작성자 댓글을 상단에 고정하여 렌더링
function renderComments() {
  // 작성자(isAuthor: true) 댓글이 배열 앞쪽으로 오도록 정렬
  const sortedComments = [...state.comments].sort((a, b) => {
    if (a.isAuthor === b.isAuthor) return 0;
    return a.isAuthor ? -1 : 1; // 작성자 댓글 우선
  });

  const commentList = $("#commentList");
  commentList.innerHTML = sortedComments.map(c => `
    <li class="comment-item ${c.isAuthor ? 'pinned-comment' : ''}">
      <div class="header">
        <strong>${c.writer}</strong>
        ${c.isAuthor ? '<span class="badge">작성자 고정</span>' : ''}
        <span class="date">${c.date}</span>
      </div>
      <p class="text">${c.text}</p>
    </li>
  `).join("");
}

// 3. 댓글 등록 이벤트: onsubmit을 사용하여 이벤트 중복 바인딩 원천 차단
$("#commentForm").onsubmit = function (e) {
  e.preventDefault();
  
  const input = $("#commentInput");
  const text = input.value.trim();
  if (!text) return;

  // 새 댓글 생성 (작성자 댓글로 지정)
  const newComment = {
    id: Date.now(),
    writer: "작성자",      // 필요에 따라 변경
    date: TODAY + " (방금)",
    text,
    isAuthor: true         // 상단 고정 플래그
  };

  state.comments.push(newComment);
  input.value = "";
  
  renderComments();
  showToast("댓글이 등록되었습니다.");
};