import { Component } from "../core/component"; import { apiService } from "../services/api.service"; export class PaginationComponent extends Component { constructor(id, {items}) { super(id); this.limit = 5; this.items = items; } async init() { await this.insertPages(); this.$pages = this.$el.querySelectorAll('li'); this.$el.addEventListener('click', this.buttonHandler.bind(this)); this.$el.querySelector('li').nextElementSibling.classList.add('active'); } buttonHandler(e) { e.preventDefault(); if (e.target.dataset.move) { const page = parseInt(e.target.dataset.move), target = e.target.parentNode; this.removeActive(); target.classList.add('active'); this.moveTo(page); } else if (e.target.tagName.toLowerCase() === 'i') { const moveType = e.target.parentNode.dataset.type, page = parseInt(this.$el.dataset.page); moveType === 'prev' ? this.movePrev(page, this.$pages) : this.moveNext(page, this.$pages); } } updatePage(value) { this.$el.setAttribute('data-page', value); } removeActive() { this.$pages.forEach(li => li.classList.remove('active')); } setActive(li, value) { li.forEach(li => {const page = parseInt(li.querySelector('a').dataset.move);page === value ? li.classList.add('active') : false;}); } movePrev(value, li) { if (value === 1) { return 0; } else { --value; this.removeActive(); this.setActive(li, value); this.updatePage(value); this.itemsInit(value); } } moveTo(value) { this.updatePage(value); this.itemsInit(value); } moveNext(value, li) { const length = this.$pages.length - 2; if (value === length) { return 0; } else { ++value; this.removeActive(); this.setActive(li, value); this.updatePage(value); this.itemsInit(value); } } async insertPages() { const pages = await apiService.getItems(), count = pages.length / this.limit; let html = ''; // назад html += '
  • chevron_left
  • '; // все страницы for (let i = 1; i <= count; i++) { html += `
  • ${i}
  • `; } // вперед html += '
  • chevron_right
  • '; this.$el.insertAdjacentHTML('afterbegin', html); } // определяем методы для инициализации наших компонентов itemsInit(value) { this.items.onShow(); this.items.insertItems(value); this.items.onHide(); } }