해당 포스트는 제로베이스 오프라인스쿨 진행 과정 중 JS PairProgramming과제를 진행하며 회고를 정리하는 글이다.
06 Stopwatch TIL
1. style.display
DOM요소에서 style.display 어트리뷰트를 불러오려고 하는 것은 CSS에서 참조하여 불러오는 것이 아닌 HTML 어트리뷰트에 있는것을 불러오는 것으로 확인이 되었다.
console.log($laps.style.display); // 아무것도 출력 안됨
$laps.style.display = 'grid';
console.log($laps.style.display); // grid
상기 코드에서 1번째 console.log를 출력해보면 아무것도 출력("")이 되지 않지만 2번째 console.log에서는 grid가 출력이 된다. 즉, laps.style.display에 "grid"를 할당하면 HTML 어트리뷰트로 추가된다.
<div class="laps" style="display: grid;"></div>
2. Closer
setInterval 함수를 사용하여 스톱워치를 구현 할 때 증가되는 시간을 어떻게 관리를 하면 좋을지 생각을 하다가 안전하게 관리를 하기위해 Closer를 사용하였다.
- 안전한 관리 : time, lapCount, timerId는 let으로 선언된 변수이다. let으로 선언된 변수는 의도치 않게 값이 변경될 수 있는 위험성을 지니고 있다. 위험성을 줄이기 위해 closer로 외부에서 변경할 수 없도록 했다.
3. isTimerStart
왼쪽 버튼이 Start이면 오른쪽 버튼은 Reset이고 왼쪽 버튼이 Stop이면 오른쪽 버튼은 Lap 임을 파악하기 위해 isTimerStart라는 체크 변수를 하나 생성하여 관리를 하였다.
if (isTimerStart) {
// isTimerStart = true $control[0] = Stop
$control[0].textContent = 'Start';
$control[1].textContent = 'Reset';
// timerStop
timer.stop();
} else {
// isTimerStart = false $control[0] = Start
$control[0].textContent = 'Stop';
$control[1].textContent = 'Lap';
$control[1].disabled = false;
}
스톱워치의 경과 시간을 mm:ss:ms으로 표시하기 위해 전에 사용해보았던 padStart 메서드를 사용하여 구현을 쉽게 할 수 있었다.
4. 리펙토링
const $control = document.querySelectorAll('.control');
if (isTimerStart) {
// isTimerStart = true $control[0] = Stop
$control[0].textContent = 'Start';
$control[1].textContent = 'Reset';
// timerStop
timer.stop();
} else {
// isTimerStart = false $control[0] = Start
$control[0].textContent = 'Stop';
$control[1].textContent = 'Lap';
$control[1].disabled = false;
// timerStart
timer.start();
}
위 방식은 $control의 0번째 인덱스와 1번째 인덱스의 값이 정확히 어떤 것인지 알 수 없다.
가독성을 개선하기 위해 $control 요소들을 각각 변수로 만들었다.
const [$mainControl, $assistControl] = document.querySelectorAll('.control');
if (isTimerStart) {
// isTimerStart = true $control[0] = Stop
$mainControl.textContent = 'Start';
$assistControl.textContent = 'Reset';
// timerStop
timer.stop();
} else {
// isTimerStart = false $control[0] = Start
$mainControl.textContent = 'Stop';
$assistControl.textContent = 'Lap';
$assistControl.disabled = false;
// timerStart
timer.start();
}
<배운점>
++ Javascript에서 style을 통해 CSS를 동적으로 추가한다는 것은 결국 HTML의 어트리뷰트 속성을 이용한다는 것을 알았다.
++ Closer로 변수를 안전하게 관리하는 것이 중요하다고 생각하게 되었다.
'JavaScript > PairProgramming1 회고' 카테고리의 다른 글
Toast (0) | 2023.05.09 |
---|---|
Tabs (0) | 2023.05.09 |
PopupModal (0) | 2023.05.09 |
DarkMode (0) | 2023.05.09 |
Is Palindrome (0) | 2023.05.09 |