95 lines
3.3 KiB
JavaScript
95 lines
3.3 KiB
JavaScript
// components/likes/controller.js
|
|
export class LikesController {
|
|
constructor(model, view) {
|
|
this.model = model;
|
|
this.view = view;
|
|
this.init();
|
|
}
|
|
|
|
async init() {
|
|
if (window.location.pathname.includes('likes.html')) {
|
|
await this.loadLikes();
|
|
this.setupLikesEventListeners();
|
|
}
|
|
|
|
if (window.location.pathname.includes('catalog.html')) {
|
|
this.setupCatalogEventListeners();
|
|
}
|
|
}
|
|
|
|
async loadLikes() {
|
|
const items = await this.model.getLikesItems();
|
|
this.view.showLikes(items);
|
|
}
|
|
|
|
setupLikesEventListeners() {
|
|
document.addEventListener('click', async (e) => {
|
|
const likeItem = e.target.closest('.like-item');
|
|
if (!likeItem) return;
|
|
|
|
const productId = likeItem.dataset.id;
|
|
|
|
// удалить
|
|
if (e.target.closest('.remove-like-btn')) {
|
|
await this.model.removeFromLikes(productId);
|
|
this.view.showNotification('Товар удален из избранного');
|
|
await this.loadLikes();
|
|
}
|
|
|
|
// перенести в корзину
|
|
if (e.target.closest('.move-to-basket-btn')) {
|
|
const items = await this.model.getLikesItems();
|
|
const product = items.find(item => item.id === productId);
|
|
if (product) {
|
|
await this.model.moveToBasket(product);
|
|
this.view.showNotification('Товар перенесен в корзину');
|
|
await this.loadLikes();
|
|
}
|
|
}
|
|
});
|
|
}
|
|
|
|
setupCatalogEventListeners() {
|
|
document.addEventListener('click', async (e) => {
|
|
const card = e.target.closest('.card');
|
|
if (!card) return;
|
|
|
|
if (e.target.closest('.like-btn')) {
|
|
const product = this.extractProductData(card);
|
|
if (product) {
|
|
await this.model.addToLikes(product);
|
|
this.view.showNotification('Товар добавлен в избранное!');
|
|
}
|
|
}
|
|
});
|
|
}
|
|
|
|
extractProductData(card) {
|
|
try {
|
|
const name = card.querySelector('.card-title').textContent;
|
|
const priceText = card.querySelector('.text-muted').textContent.replace('$', '');
|
|
const description = card.querySelector('.card-text').textContent;
|
|
const image = card.querySelector('img').src;
|
|
|
|
// ✅ Вытаскиваем category и condition
|
|
const category = card.querySelector('.col-6:nth-child(1) p')?.textContent.trim() || '';
|
|
const condition = card.querySelector('.col-6:nth-child(2) p')?.textContent.trim() || '';
|
|
|
|
const id = btoa(`${name}-${priceText}`).substring(0, 8);
|
|
|
|
return {
|
|
id: id,
|
|
name: name.trim(),
|
|
price: parseFloat(priceText),
|
|
description: description.trim(),
|
|
image: image,
|
|
category: category,
|
|
condition: condition
|
|
};
|
|
} catch (error) {
|
|
console.error('Ошибка при извлечении данных товара:', error);
|
|
return null;
|
|
}
|
|
}
|
|
}
|