-
[js] mvc 패턴을 연습해보자 -2 검색결과(1)Javascript 2023. 7. 19. 23:42
이 페이지에서 구현할 요구사항이다.
● 검색 결과가 검색폼 아래 위치한다. 검색 결과가 없을 경우와 있을 경우를 구분한다.
index.html에 div태그를 추가해준다.
<div class="content"><div id="search-result-view"></div></div>아직 데이터를 받기 전,
storage.js 파일 안에 데이터가 담겨있다.
다음 사진은 데이터 중 일부이다.
import { createPastDate } from "./helpers.js";
const storage = {keywordData: [{ id: 1, keyword: "샐러드" },{ id: 2, keyword: "커리" },{ id: 3, keyword: "햄버거" },],
historyData: [{ id: 1, keyword: "검색기록1", date: createPastDate(3) },{ id: 2, keyword: "검색기록2", date: createPastDate(2) },{ id: 3, keyword: "검색기록3", date: createPastDate(1) },],
productData: [{id: 1,name: "비건 샐러드",imageUrl:},};
export default storage;다음은 아직 데이터를 받기 전인 SearchResultView.js 파일이다.
import { qs } from "../helpers.js"import View from "./View.js";
export default class SearchResultView extends View {constructor () {super(qs('#search-result-view'))
this.template = new Template()}
show(data = []) {this.element.innerHTML = data.length > 0? this.template.getList(data): this.template.getEmptyMessage();super.show();}}
class Template {getEmptyMessage() {return `<div class="empty-box">검색결과가 없습니다.</div>`}
getList(data = []) {return `<ul class='result'>${data.map(this._getItem).join("")}</ul>`
}_getItem({imageUrl, name}) {return `<li><img src="${imageUrl}" alt="${name}" /><p>${name}</p></li>`}
}template이라는 새로운 클래스를 만들고 그 안에 검색결과를 보여주는 메서드들을 생성하였다.
다음은 Controller.js 파일에서 search에 추가된 모습이다.
search(searchKeyword) {console.log(tag, "search",searchKeyword);this.store.search(searchKeyword);this.render()}여기서 render는
render() {if(this.store.searchKeyword.length > 0) {this.searchResultView.show(this.store.searchResult)return}this.searchResultView.hide();}show와 hide는 모두 강의에서 제공되는 helper 함수이다.
여기까지
● 검색 결과가 검색폼 아래 위치한다. 검색 결과가 없을 경우와 있을 경우를 구분한다.
기능을 구현 완료하였다.
-참고 인프런 김정환 "만들고 비교하며 학습하는 리액트"
'Javascript' 카테고리의 다른 글
[js] mvc 패턴을 연습해보자 -3 탭(2) (0) 2023.07.20 [js] mvc 패턴을 연습해보자 -3 탭(1) (0) 2023.07.20 [js] mvc 패턴을 연습해보자 -2 검색결과(2) (0) 2023.07.20 [js] mvc 패턴을 연습해보자 -1 검색폼 (0) 2023.07.19 [js]해커뉴스 코딩 복습 (0) 2023.07.05