@3/14/2023
댓글 삭제 기능 추가
•
댓글 삭제 버튼
<button th:onclick="|location='@{/posts/{postId}/comments/{commentId}/delete(postId = ${post.id}, commentId = ${commentListDTO.commentId})}'|"
class="btn btn-sm">삭제</button>
Java
복사
•
컨트롤러
@GetMapping("/posts/{postId}/comments/{commentId}/delete")
public String deleteComment(
@PathVariable Long postId,
@PathVariable Long commentId
) {
commentService.deleteComment(commentId);
return "redirect:/posts/" + postId;
}
Java
복사
댓글 수정
•
수정 버튼을 누르면 댓글 출력 부분을 textarea를 포함한 form으로 변경
◦
template 태그 이용
◦
부모, 자식 객체를 선택할 때 가급적 순서 기반이 아닌 태그 기반으로 함(html 수정 시 충격 최소화)
◦
수정 시에는 다른 댓글의 수정, 삭제 버튼 비활성화(클래스로 묶어서 for문 돌림). 취소 시 다시 활성화
let commentButtons = document.getElementsByClassName('comment-button');
for (let button of commentButtons) {
button.style.pointerEvents = 'none';
}
JavaScript
복사
•
컨트롤러
PostMapping("/posts/{postId}/comments/{commentId}/edit")
public String editComment(
@PathVariable Long postId,
@PathVariable Long commentId,
@ModelAttribute CommentUpdateDTO commentUpdateDTO
) {
commentService.updateComment(commentUpdateDTO);
return "redirect:/posts/" + postId;
}
Java
복사
•
javascript
<script th:inline="javascript">
function editComment(button, commentId) {
let parent = button.parentElement;
let contentEl = parent.lastElementChild;
let content = contentEl.innerText;
contentEl.style.display = 'none';
let form = document.getElementsByTagName('template')[0].content.cloneNode(true).firstElementChild;
let editTextarea = form.getElementsByTagName('textarea')[0];
editTextarea.innerText = content;
let hiddenInput = form.getElementsByTagName('input')[0];
hiddenInput.value = commentId;
form.action = '/posts/[[${postId}]]/comments/' + commentId + '/edit';
parent.appendChild(form);
let commentButtons = document.getElementsByClassName('comment-button');
for (let button of commentButtons) {
button.style.pointerEvents = 'none';
}
}
function cancelEdit(button) {
let li = button.closest('li');
li.getElementsByTagName('p')[0].style.display = '';
li.getElementsByTagName('form')[0].remove();
let commentButtons = document.getElementsByClassName('comment-button');
for (let button of commentButtons) {
button.style.pointerEvents = '';
}
}
</script>
JavaScript
복사
•
수정 템플릿
<template>
<form class="input-group col-12 col-6 mb-2" method="post">
<textarea type="text" name="content" class="form-control" rows="3" style="resize: none"
aria-label="Recipient's username with two button addons"></textarea>
<button class="btn btn-outline-secondary" type="button" onclick="submit()">완료</button>
<button class="btn btn-outline-danger" type="button" onclick="cancelEdit(this)">취소</button>
<input type="hidden" name="commentId"/>
</form>
</template>
HTML
복사
•
결과물