다음으로 var을 const로 수정했을 때 fields의 변수 저장 과정이 올바른지 확인하는 방법이 필요했습니다. 그래서 아래와 같은 코드를 const를 사용했을 때 기능적인 면에서 오류가 나타나지 않도록 수정하는 방법을 질문하였습니다.
const fields = {
name: { el: document.getElementById('name'), msg: document.getElementById('nameMsg'), touched: false },
email: { el: document.getElementById('email'), msg: document.getElementById('emailMsg'), touched: false },
password: { el: document.getElementById('password'), msg: document.getElementById('passwordMsg'), touched: false },
confirm: { el: document.getElementById('confirm'), msg: document.getElementById('confirmMsg'), touched: false }
};
<aside> 💡
DOM 로드 시점과 엘리먼트 부재 시의 런타임 에러를 방지하기 위해 몇 가지 보완할 점이 있습니다.
개선 코드
document.addEventListener('DOMContentLoaded', () => {
const fields = {
name: { el: document.getElementById('name'), msg: document.getElementById('nameMsg'), touched: false },
email: { el: document.getElementById('email'), msg: document.getElementById('emailMsg'), touched: false },
password: { el: document.getElementById('password'), msg: document.getElementById('passwordMsg'), touched: false },
confirm: { el: document.getElementById('confirm'), msg: document.getElementById('confirmMsg'), touched: false }
};
// 이후 폼 이벤트 리스너 등록 로직 작성
});
개선 코드 방법 중에 3가지를 추천 받게 되었습니다. 첫 번째로는 DOM 로드가 완료된 후 실행을 보장해야 DOM이 준비된 시점에 안전하게 초기화시키는 방식인데 저는 이미 위에서 DOM 요소들을 해당 index.html 파일에 맞춰 사용할 수 있게 수정하였고 DOM은 이미 준비가 된 시점이었습니다. 그래서 그 시점에 안전하게 초기화 시키는 방식을 먼저 고려하여 코드 식을 작성하고자 DOM 로드가 완료된 후 실행 보장을 DOM 요소 위에 작성하는지 아래에 작성하는지 질문하게 되었습니다.
하지만 질문의 방식이 잘못되었는지 원하는 답변을 받지 못하였고, **DOM이 준비된 시점이 DOM 요소가 작성된 후 인가요? 전인가요?**로 수정하여 질문하게 되었습니다.
<aside> 💡
DOM 요소가 작성(파싱)된 "후"입니다.
브라우저는 HTML 문서를 위에서부터 아래로 한 줄씩 읽어가며 태그들을 메모리상의 'DOM 트리' 객체로 변환합니다.
</aside>
작성 위치를 확인하여 DOM 요소가 작성된 “후”에 해당 코드를 작성하였고 다음으로 추천 받은 팩토리 함수/루프를 활용한 리팩토링은 이벤트 리스너인지 확인하는 작업을 진행했습니다. 이유는 DOM 로드가 완료된 후 실행 보장하고 이벤트 리스너가 등록되어 로직을 작성해야 하는데 팩토리 함수와 루프를 활용한 리팩토링에 대한 적은 양의 정보를 통해 해당 코드 구간을 작성하기 힘들었기 때문입니다.
아래는 Gemini 교수님이 주신 코드를 통해 작성한 코드 입니다.
/* -- DOM 로드 완료 후 실행 -- */
document.addEventListener('DOMContentLoaded', () => {
const fieldKeys = ['name', 'email', 'password', 'confirm'];
// 루프를 활용해 fields 객체 생성 (데이터 가공)
const fields = fieldKeys.reduce((acc, key) => {
acc[key] = {
el: document.getElementById(key),
msg: document.getElementById(`${key}Msg`),
touched: false
};
return acc;
}, {});