반응형
Notice
Recent Posts
Recent Comments
Link
taenyLog
자바스크립트 코드 중복 줄이기 - 리팩토링 본문
반응형
plate는 45 35 25 15 10 5개 가있고 아래의 이벤트리스너를 5개 만들어야하는 상황이였음
plate45.button.addEventListener("click", function () {
totalKg += plate45.weight;
totalKgDisplay.textContent = totalKg;
const btn = document.createElement("BUTTON");
btn.innerHTML = "45lbs";
btn.class = "45lbs";
document.body.appendChild(btn);
btn.addEventListener("click", function () {
document.body.removeChild(btn);
totalKg -= 20 * 2;
totalKgDisplay.textContent = totalKg;
});
});
plate35.button.addEventListener("click", function () {
totalKg += plate35.weight;
totalKgDisplay.textContent = totalKg;
const btn = document.createElement("BUTTON");
btn.innerHTML = "35lbs";
btn.class = "35lbs";
document.body.appendChild(btn);
btn.addEventListener("click", function () {
document.body.removeChild(btn);
totalKg -= 15 * 2;
totalKgDisplay.textContent = totalKg;
});
});
const createButtonGroup = (weight, count) => {
const btns = [];
for (let i = 0; i < count; i++) {
const btn = document.createElement("button");
btn.innerHTML = `${weight}lbs`;
btn.classList.add(`${weight}lbs`);
document.body.appendChild(btn);
btns.push(btn);
}
const btnClickHandler = () => {
btns.forEach((btn) => {
document.body.removeChild(btn);
});
totalKg -= weight;
totalKgDisplay.textContent = totalKg;
};
btns.forEach((btn) => {
btn.addEventListener("click", btnClickHandler);
});
};
const addButtonClickListener = (plate) => {
const { weight, button } = plate;
button.addEventListener("click", () => {
totalKg += weight;
totalKgDisplay.textContent = totalKg;
createButtonGroup(weight, 2);
});
};
const plates = [
{
weight: 20 * 2,
button: document.querySelector("#plate45"),
},
{
weight: 15 * 2,
button: document.querySelector("#plate35"),
},
{
weight: 11.34 * 2,
button: document.querySelector("#plate25"),
},
{
weight: 6.8 * 2,
button: document.querySelector("#plate15"),
},
{
weight: 4.53 * 2,
button: document.querySelector("#plate10"),
},
];
plates.forEach(addButtonClickListener);
코드의 중복을 줄임
반응형
'Web' 카테고리의 다른 글
JS 프로젝트 | lb to kg (0) | 2023.06.18 |
---|---|
자바스크립트 오류 해결 | Uncaught DOMException: (0) | 2023.06.18 |
자바스크립트 변수 생성 코드 리팩토링 (0) | 2023.06.17 |
JavaScript 요소추가 (0) | 2023.06.17 |
JavaScript 버튼 생성 (0) | 2023.06.15 |