Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[14기 정새미] step1 돔 조작과 이벤트 핸들링으로 메뉴 관리하기 #274

Open
wants to merge 7 commits into
base: eddington524
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -244,3 +244,11 @@ live-server 폴더명
## 📝 License

This project is [MIT](https://github.com/blackcoffee-study/moonbucks-menu/blob/main/LICENSE) licensed.

# 팀이름: N^6
- 김성중
- 김동욱
- 정요한
- 정새미
- 전상혁
- 서진규
4 changes: 4 additions & 0 deletions src/css/index.css
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,10 @@ hr {
background-color: lightgray;
}

ul{
list-style: none;
}

ul li button {
width: 60px;
line-height: inherit;
Expand Down
79 changes: 79 additions & 0 deletions src/js/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
const $ = (selector) => document.querySelector(selector);

function App() {

const createMenuName = () => {

if($("#espresso-menu-name").value === ""){
alert("값을 입력해주세요");
return;
}

const espressoMenuName = $("#espresso-menu-name").value;

$("#espresso-menu-list").insertAdjacentHTML("beforeend", menuItemTemplate(espressoMenuName));
updateMenuCount();
$("#espresso-menu-name").value = "";

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

input.value 를 활용하여 값을 비워주는 방식도 좋지만, 우리가 사용하는 HTMLFormElement 스펙에서는 reset 이라는 메서드를 지원하여 form 요소를 기본 값으로 초기화하기도 합니다. HTML 의 기본 스펙은 생각보다 많은 기능을 지원하여 알아두면 도움이 될 것 같아요.

};

const updateMenuCount = () => {
const menuCount = $("#espresso-menu-list").querySelectorAll('li').length;
$(".menu-count").innerText = `총 ${menuCount} 개`
};

const menuItemTemplate = (espressoMenuName) => {
return `<li class="menu-list-item d-flex items-center py-2">
<span class="w-100 pl-2 menu-name">${espressoMenuName}</span>
<button
type="button"
class="bg-gray-50 text-gray-500 text-sm mr-1 menu-edit-button"
>
수정
</button>
<button
type="button"
class="bg-gray-50 text-gray-500 text-sm menu-remove-button"
>
삭제
</button>
</li>`
};
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

제안드립니다
이 함수를 표현해보면

// espressMenuName 문자열을 받아서 템플릿리터럴로 쓰여진 html코드 문자열을 반환하는 함수
type menuItemTemplate = (espressMenuName : string ) => string

이런 식으로 볼 수 있을 거같아요. 그럼 get- 접두사prefix 붙이는게 더 좋은 네이밍일거 같아요 getMenuItemTemplate.
혹시 접두사를 일부러 사용하지 않은 이유가 있다면 궁금합니다

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

네네! 말씀해주신대로 prefix를 붙이는게 더 좋은 것 같아요~ 감사합니다!


const removeMenuName = (e) => {
e.target.closest("li").remove();
updateMenuCount();
};

const editMenuName = (e) =>{
const $menuName = e.target.closest("li").querySelector(".menu-name");
const editedName = prompt("메뉴명을 수정하세요", $menuName.innerText);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

innerText 보다는 가급적 textContent 를 이용하시는게 미래에 있을 예상하지 못할 버그나 성능문제를 막는데에 조금 더 도움이 될 거에요.

$menuName.innerText = editedName;

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

prompt를 취소한다면 메뉴명이 null 값으로 변경될 수도 있을 것 같습니다 !

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

아하 null값 체크를 못했네요! 감사합니다! if(!editedName) return; 이렇게 체크해보겠습니다~

};

$("#espresso-menu-list").addEventListener("click", (e) => {
if (e.target.classList.contains("menu-edit-button")){
editMenuName(e);
}

if(e.target.classList.contains("menu-remove-button")){
if(confirm("정말 삭제하시겠습니까?")){
removeMenuName(e);
}
}
});

// form 태그가 자동으로 전송되는 걸 막기
$("#espresso-menu-form").addEventListener("submit", (e) => {
e.preventDefault();
})

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

HTMLFormElement 의 submit 은 기본 스펙으로 엔터키와 submit 버튼을 눌렀을 때를 모두 지원합니다. 그래서 onsubmit 이벤트에 콜백 함수를 기록해두면, onclickkeydown 이벤트 두개를 잡을 필요가 없어지죠. 다만, 현재 html 에서 버튼의 type 이 submit 이 아닌데, 그것만 바꿔주면 잘 동작 할 거예요.

// 메뉴의 이름을 입력 받기
$("#espresso-menu-name").addEventListener("keydown", (e) => {
if(e.key !== "Enter") return;
createMenuName();
});

$("#espresso-menu-submit-button").addEventListener("click", createMenuName);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

submit 이벤트에 createMenuName 함수를 넣어주면 더 간결하지 않을까요?

Copy link
Author

@Eddington524 Eddington524 Jul 19, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

submit이벤트에서 createMenuName를 호출하는것을 말씀하시는 것일까요? :)
submit 이벤트 부분은 form 태그 때문에 자동으로 새로고침되는 부분을 막기위해서 e.preventDefault(); 만 넣고 입력받는 이벤트는 아래의 keydown과 click에서만 createMenuName을 호출하고 있어서~ 호출할 필요는 없을 것 같습니다~

Copy link

@joseph-106 joseph-106 Jul 19, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
// form 태그가 자동으로 전송되는 걸 막기
$("#espresso-menu-form").addEventListener("submit", (e) => {
e.preventDefault();
})
// 메뉴의 이름을 입력 받기
$("#espresso-menu-name").addEventListener("keydown", (e) => {
if(e.key !== "Enter") return;
createMenuName();
});
$("#espresso-menu-submit-button").addEventListener("click", createMenuName);
// form 태그가 자동으로 전송되는 걸 막기
$("#espresso-menu-form").addEventListener("submit", (e) => {
e.preventDefault();
createMenuName();
})

아아 동작은 동일하지만 아마 이렇게 줄이면 조금 더 간결하지 않을까 하는 의미였습니다 !

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

form 요소 안의 input에 Enter keydown이벤트를 받는 방식을, 위에 106님이 하신 것처럼 할 수 있습니다
ref: https://codesandbox.io/s/input-in-form-2o9x9i

는 이미 달아주셧군요

}

App();