Javascript

[js] mvc 패턴을 연습해보자 -2 검색결과(2)

popeyes 2023. 7. 20. 00:05

오늘 구현할 요구사항이다. 

● x버튼을 클릭하면 검색폼이 초기화 되고, 검색 결과가 사라진다

 

x버튼을 클릭했을 때의 플로우를 점검해보자.

 

x버튼은 SearchFormView에서 관리하고 있다.

아래 코드의 마지막 줄은 이벤트를 바인딩하는 메서드다.

export default class SearchFormView extends View {
constructor() {
super(qs("#search-form-view"));

this.inputElement = qs("[type=text]", this.element);
this.resetElement = qs("[type=reset]", this.element);
this.showResetButton(false);
this.bindEvent();
}

아래 코드에서 여기서 reset이 시작되면 handleReset이 호출된다.

bindEvent() {
on(this.inputElement, "keyup", () => this.handleKeyup());
this.on("submit", event => this.handleSubmit(event))

this.on("reset", () => this.handleReset());
 
}

 

handleReset() {
this.emit("@reset");
}

handleReset은 별다른 역할 없이 커스텀이벤트 @reset만 발행한다.

 

이젠 이를 구독하고있는 Controller.js 로 가보자.

 

export default class Controller {
constructor(store, { SearchFormView, searchResultView }) {
console.log(tag);

this.store = store;

this.SearchFormView = SearchFormView;
this.searchResultView = searchResultView;

this.subscribeViewEvents();
}

쭈루룩 나오고 마지막에 이벤트를 구독하는 메서드가 있다.

그 메서드는 아래와 같다.

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

여기서는 this.reset으로 가게된다.

이제 해당 부분을 보자.

 

여기서부터 오늘 구현할 요구사항의 시작이다.

reset() {
console.log(tag, "reset");
this.store.searchKeyword = "";
this.store.searchResult = [];
this.render();
}

store에 있는 searchKeyword 와 searchResult를 초기화 시키고,

렌더링을 다시해주면 오늘의 요구사항인

 

● x버튼을 클릭하면 검색폼이 초기화 되고, 검색 결과가 사라진다

 

구현을 완료하였다.

 

 

 

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