inblog logo
|
taker
    스프링부트

    블로그 V4 목록페이지 코드 개선

    김인범's avatar
    김인범
    Nov 25, 2024
    블로그 V4 목록페이지 코드 개선
    Contents
    기존개선
    기존의 블로그 목록페이지에서 로드되는 코드들을 개선해봅니다.

    기존

    • renderList ⇒ 목록페이지 골자만 가져오는 코드
    // list 디자인 function renderList(){ clear(); let dom = ` <table border="1"> <thead> <tr> <th>번호</th> <th>제목</th> <th></th> </tr> </thead> <tbody id="list-box"> <!--id값 넣을때는 컨벤션/ 카멜X--> </tbody> </table> `; root.innerHTML = dom; sendList(); }
    • renderListItem ⇒ <tbody id=”list-box”>에 글 데이터들 나열해주는 코드
    function renderListItem(board){ let dom = ` <td>${board.id}</td> <td>${board.title}</td> <td><a href="javascript:void(0);" onclick="renderDetail(${board.id})">상세보기</a></td> `; let item = document.createElement("tr"); item.innerHTML = dom; return item; }
    • sendList ⇒ 서버에 게시글 데이터들 요청하는 메서드
    async function sendList(){ // 1. API 요청 let response = await fetch("http://localhost:8080/api"); let responseBody = await response.json(); // 2. 응답 처리 let boards = responseBody.body; let listBox = document.querySelector("#list-box"); boards.forEach(board => { let item = renderListItem(board); listBox.append(item); }); }
     
    기존에는 sendlist를 통해 서버에서 불러올 때 forEach를 통해 하나씩 페이지에 뿌려주는 방식이었습니다.
     

    개선

    • renderList
    // list 디자인 async function renderList() { clear(); let boards = await sendList2(); let dom = ` <table border="1"> <thead> <tr> <th>번호</th> <th>제목</th> <th></th> </tr> </thead> <tbody id="list-box"> ${boards.map(b => renderListItem2(b)).join("")} </tbody> </table> `; root.innerHTML = dom; }
    async function sendList2() { // 1. API 요청 let response = await fetch("http://localhost:8080/api"); let responseBody = await response.json(); // 2. 응답 처리 let boards = responseBody.body; return boards; }
    기존의 sendList 메서드에서 forEach문을 빼서 간결하게 만들었습니다.
    renderList() 메서드에서 반복문으로 처리하여
    1. API를 요청하는 sendList2 메서드가 간결해집니다.
    1. 브라우저에서는 각 항목 별로 렌더링 작업을 반복하지 않아도 됩니다.
    1. DOM 업데이트를 한번만 하도록 설계되어 브라우저에 사용되는 비용을 줄일 수 있습니다.
     
    Share article

    taker

    RSS·Powered by Inblog