Javascript

[js] mvc 패턴을 연습해보자 -4 최근 검색어(2)

popeyes 2023. 7. 21. 11:55

요구사항

● 목록에서 x 버튼을 클릭하면 선택된 검색어가 목록에서 삭제된다

 

HistoryListView.js 파일에

bindEvent를 생성해준다

 

 
bindEvent() {
delegate(this.element, "click", "button.btn-remove", event => this.handleClickRemoveButton(event))

super.bindEvent();
}

delegate는 강의에서 제공해주는 헬퍼함수.

그 후 부모의 bindEvent로 오버라이딩 해준다.

 

handleClickRemoveButton(event) {
console.log(tag, "handleClickRemoveButton",event.target);
const value = event.target.parentElement.dataset.keyword
this.emit('@remove', {value});
}

remove 커스텀이벤트를 발행시킨다.

이제 이 부분을 관리하는 Controller.js 안에 subscribeViewEvents로 가보자

 

subscribeViewEvents() {
this.SearchFormView.on("@submit", (event) =>
this.search(event.detail.value))
.on("@reset", () => this.reset());

this.tabView.on('@change', event =>
this.changeTab(event.detail.value))

this.keywordListView.on('@click', event => this.search(event.detail.value));
this.historyListView.on("@click", (event) =>
this.search(event.detail.value))
.on("@remove", (event) => this.removeHistory(event.detail.value));

 
}

아래 코드를 추가 시켜 주었다.

 

this.historyListView.on("@click", (event) =>
this.search(event.detail.value))
.on("@remove", (event) => this.removeHistory(event.detail.value));

이렇게 되면 remove 커스텀이벤트가 실행이 될때 removeHistory 메서드가 실행이된다.

removeHistory(keyword) {
this.store.removeHistory(keyword);
this.render();
}

이 메서드는 또 store안에 있는 removeHistory를 실행시킨다. 그럼 store로 가보자.

 

removeHistory(keyword) {
this.storage.historyData = this.storage.historyData.filter(
history => history.keyword !== keyword)
}

위 코드는 store.js 안에 있는 removeHistory이다.

storage.js 안에 있는 historyData를 필터링 해준다.

historyData: [ //최근 검색어
{ id: 1, keyword: "검색기록1", date: createPastDate(3) },
{ id: 2, keyword: "검색기록2", date: createPastDate(2) },
{ id: 3, keyword: "검색기록3", date: createPastDate(1) },
],

이렇게 한 후 Controller.js 에서 다시 render를 호출하면,

 

구현 완료!

 

 

 

-참고 인프런 김정환 "만들고 비교하며 학습하는 리액트"