const onClick = e => {
const {
code,
className,
value,
dataset: { key: isLeft }
} = e.target;
if (className == 'arrow') {
do somthing
}
if (code == 'Enter') {
func(value);
}
}
class SearchResult {
$searchResult = null;
data = null;
onClick = null;
images = new Set();
isRequesting = false;
constructor({ $target, initialData, onClick, onRandom }) {
this.$searchResult = document.createElement('section');
this.$searchResult.className = 'SearchResult';
$target.appendChild(this.$searchResult);
this.data = initialData;
this.onClick = onClick;
this.onRandom = onRandom;
this.$searchResult.onclick = this.handleOnClick;
this.render();
console.log('[CREATED]', 'SearchResult', this);
}
handleOnClick = ({ target }) => {
if (target.tagName == 'IMG') {
console.log('SearchResult', target.dataset);
this.onClick(this.data[target.dataset.key.split('_')[1]]);
}
};
setState(nextData) {
this.data = nextData;
this.render();
console.log('[UPDATED]', 'searchResult ', { nextData });
}
clearResults = () => {
console.log('clearResults');
this.$searchResult.innerHTML = '';
};
createItem = (cat, i) => {
const article = document.createElement('article');
article.classList.add('item');
const img = new Image();
img.src = window.cats.LAZY_IMG_SRC;
img.dataset.src = cat.url;
img.alt = cat.name;
img.title = cat.name;
img.dataset.key = `${cat.id}_${i}`;
this.images.add(img);
article.appendChild(img);
return article;
};
createNoItem = () => {
const article = document.createElement('article');
article.classList.add('NoItem');
article.style = 'flex:1; justify-content: center; display: flex;';
const h1 = document.createElement('h1');
h1.innerText = '검색결과 없음';
article.appendChild(h1);
return article;
};
loadLazyImages = (entries, observer) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
let lazyImage = entry.target;
lazyImage.src = lazyImage.dataset.src;
this.images.delete(lazyImage);
lazyImage.classList.remove('lazy');
observer.unobserve(lazyImage);
}
});
if (this.images.size <= 30 && !this.isRequesting) {
this.onRandom();
}
};
lazyOptions = {
threshold: 0,
trackVisibility: true,
delay: 200,
};
lazyImageObserver = new IntersectionObserver(
this.loadLazyImages,
this.lazyOptions
);
registerImagesToLazyObserver = (lazyImages, lazyImageObserver) => {
lazyImages.forEach(function (lazyImage) {
lazyImageObserver.observe(lazyImage);
});
};
lazyLoad = () => {
this.registerImagesToLazyObserver([...this.images], this.lazyImageObserver);
};
setIsRequesting = (isRequesting) => {
console.log('!! isRequesting', isRequesting);
this.isRequesting = isRequesting;
};
render() {
if (this.data == undefined || this.data.length == 0)
this.$searchResult.appendChild(this.createNoItem());
else
this.data.map((cat, i) =>
this.$searchResult.appendChild(this.createItem(cat, i))
);
this.lazyLoad();
}
}