댓글 등록, 수정, 삭제 기능을 간단히 구현하였다.
프론트단에서 댓글 수정, 삭제 버튼을 각 댓글에 어떻게 연동 시키기 위해서는 unique한 키값이 필요한데 이 값은 MongoDB의 _id값으로 사용하였다.
댓글을 등록할 때 관련 정보를 DB에 먼저 저장 후 반환된 _id값을 받아와서 다음과 같이 각 태그의 id로 지정해 주었다.
let temp_html = `<blockquote class="blockquote mb-0">
<p id="${comment_id}">${comment}</p>
<form class="hidden-comment"><textarea id="${comment_id}-hidden">${comment}</textarea>
<footer class="blockquote-footer">${name} (${time})</footer>
<button onclick="update_comment('${comment_id}')" type="button" id="${comment_id}-update-btn" class="btn btn-outline-warning">수정</button>
<button onclick="register_updated_comment('${comment_id}')" type="button" id="${comment_id}-register-btn" class="btn btn-outline-dark">등록</button>
<button onclick="delete_comment('${comment_id}')" type="button" id="${comment_id}-delete-btn" class="btn btn-outline-danger">삭제</button>
</form>
</blockquote>
<hr>`;
여기까지 하면 수정 삭제 기능은 거의 완성한 것이나 다름이 없다.
수정 버튼을 누르면 이전에 썼던 글이 자동으로 뜨게 하고 싶었는데 이 부분을 구현하는게 재미있었다.
우선 댓글의 내용 부분은 위의 코드 내용과 같이 <p>태그와 <textarea>태그에는 둘 다 담기게 했다. 평상시에는 <p>태그는 보이며 <textarea>태그는 숨겨져 있다.
아래는 댓글 수정 버튼을 누르면 실행되는 함수이다.
function update_comment(comment_id) {
document.getElementById(comment_id).style.display = 'none';
document.getElementById(comment_id + '-hidden').style.display = 'block';
document.getElementById(comment_id + '-update-btn').style.display = 'none';
document.getElementById(comment_id + '-register-btn').style.display = 'block';
document.getElementById(comment_id + '-delete-btn').style.display = 'none';
}
이 함수는 <p>태그는 숨기고 <textarea>를 보이게 하여 이전에 쓴 글에 이어서 수정할 수 있게 하였다. 또한 수정 버튼과 삭제 버튼도 숨긴다.
아래는 수정 후 등록 버튼을 누르면 실행되는 함수이다.
function register_updated_comment(comment_id) {
let comment = document.getElementById(comment_id + '-hidden').value;
$.ajax({
type: 'PATCH',
url: '/comments',
data: {comment_id_give: comment_id, comment_give: comment},
success: function (response) {
window.location.reload();
},
});
document.getElementById(comment_id).style.display = 'block';
document.getElementById(comment_id + '-hidden').style.display = 'none';
document.getElementById(comment_id + '-update-btn').style.display = 'block';
document.getElementById(comment_id + '-register-btn').style.display = 'none';
document.getElementById(comment_id + '-delete-btn').style.display = 'block';
}
이 함수는 다시 <p>태그는 보이게 하고 <textarea>를 숨기며 등록 버튼을 숨기고 수정, 삭제 버튼은 보이게 하여 평상시 댓글 모습을 보여주게 한다.
수정 기능을 수정 버튼을 누르면 이전에 썼던 글이 자동으로 뜨게 하여 이어서 글을 작성하게끔 구현하고 싶었는데 어떻게 구현할지 고민을 좀 한 것같다.
이 글을 작성하면서 위 방법을 더 효율적으로 개선하는 방법이 떠올랐다. 보통 댓글을 수정하는 경우는 많지 않으므로 처음에 댓글 내용을 <p>태그와 <textarea>태그 두 군데 모두 담는 것은 비효율적이다. 따라서 <p>태그에만 담았다가 댓글 수정하기 버튼을 누를 때 <p>태그 내용을 <textarea>태그로 가져오면 더 효율적일 것 같다.