최근 검색한 키워드를
SearchInput아래에 표시되도록 만들고, 해당 영역에 표시된 특정 키워드를 누르면 그 키워드로 검색이 일어나도록 만듭니다. 단, 가장 최근에 검색한 5개의 키워드만 노출되도록 합니다.페이지를 새로고침해도 마지막 검색 결과 화면이 유지되도록 처리합니다.
검색 히스토리를 저장하고, 노출 시키는 컴포넌트를 새롭게 생성한다. ⇒ KeywordHistory.js + index.html 연결
class KeywordHistory{
$keywordHistory = null; // 엘리먼트 생성
data = null; // 데이터
constructor({$target}){
const $keywordHistory = document.createElement('ul');
this.$keywordHistory = $keywordHistory;
this.$keywordHistory.className = 'KeywordHistory';
$target.appendChild(this.$keywordHistory);
}
}
SearchInput아래에 표시되게 하기 위해 SearchInput 컴포넌트에서 KeywordHistory 컴포넌트를 호출한다.
const TEMPLATE = '<input type="text">';
class SearchInput {
constructor({ $target, onSearch, onRandomSearch }) {
//검색 input
const $wrapper = document.createElement("section");
const $searchInput = document.createElement("input");
this.$searchInput = $searchInput;
this.$searchInput.placeholder = "고양이를 검색해보세요.|";
$wrapper.className = "SearchInputArea";
$searchInput.className = "SearchInput";
$wrapper.appendChild($searchInput);
$target.appendChild($wrapper);
$searchInput.addEventListener("keyup", e => {
if (e.keyCode === 13) {
onSearch(e.target.value);
}
});
//랜덤 버튼
const $randomButton = document.createElement("button");
this.$randomButton = $randomButton;
this.$randomButton.className = 'RandomButton';
this.$randomButton.textContent = '랜덤고양이';
$wrapper.appendChild($randomButton);
//랜덤 버튼 클릭
$randomButton.addEventListener('click', e => {
onRandomSearch();
});
// 키워드 검색 히스토리 컴포넌트 생성.
**this.KeywordHistory = new KeywordHistory({
$target
});**
}
render() {}
}

아직 키워드 데이터가 없어서 나오는게 없을 것이다. 히스토리가 없는 ul태그가 있다. 최근 검색한 키워드를 채워넣어준다.
class KeywordHistory{
$keywordHistory = null; // 엘리먼트 생성
data = null; // 데이터
constructor({$target}){
const $keywordHistory = document.createElement('ul');
this.$keywordHistory = $keywordHistory;
this.$keywordHistory.className = 'KeywordHistory';
$target.appendChild(this.$keywordHistory);
//아직 키워드 데이터가 없어서 나오는게 없다.
//더미데이터로 만들어서 노출시켜본다.
this.data = [
'아',
'고양이',
'cat'
];
this.render();
}
render(){
this.$keywordHistory.innerHTML = this.data.map( keyword => `<li><button>${keyword}</button></li>` ).join('');
}
}
console.log(this.$keywordHistory.querySelectorAll('li button'));
//결과
//NodeList(3) [button, button, button] 를 확인할 수 있다.
this.$keywordHistory.querySelectorAll('li button').forEach(($item, index) => {
$item.addEventListener('click', () => {
console.log($item); //각 노드를 확인할 수 있다.
});
});
$item을 클릭하면 각 노드 엘리먼트를 확인할 수 있다.//예 $item 클릭 시 아래와 같이 나옴.
<button>고양이</button>
this.$keywordHistory.querySelectorAll('li button').forEach(($item, index) => {
$item.addEventListener('click', () => {
console.log($item,index,this.data[index])
});
});