пагинация теперь стала независимой от других компонентов

This commit is contained in:
Sergey Yarkov 2019-12-25 15:57:50 +03:00
parent a78cd3e7c7
commit 557f7967b3
5 changed files with 54 additions and 84 deletions

View File

@ -49,7 +49,7 @@ MongoClient.connect(db_config.url, {useNewUrlParser: true, useUnifiedTopology: t
}) })
.catch((error) => { .catch((error) => {
server.get('*', (req, res) => { server.get('*', (req, res) => {
res.send('Ошибка соединения с БД. Настройте файл database.js'); res.send('Ошибка соединения с БД.');
}); });
}) })
.finally(() => { .finally(() => {

View File

@ -3,30 +3,15 @@ import { apiService } from "../services/api.service";
import { renderItems } from "../templates/items.template"; import { renderItems } from "../templates/items.template";
export class ItemsComponent extends Component { export class ItemsComponent extends Component {
constructor(id, {loader}) { constructor(id, {pagination}) {
super(id); super(id);
this.loader = loader; this.pagination = pagination;
} }
async init() { async init() {
const html = await this.getItemsByPage(1); const items = await apiService.getItems();
this.$table = this.$el.querySelector('table tbody'); this.$table = this.$el.querySelector('table tbody');
this.$table.insertAdjacentHTML('afterbegin', html); this.pagination.initialize(items.length, this.$table, this.getItemsByPage);
this.onHide();
}
onHide() {
this.loader.hide();
}
onShow() {
this.loader.show();
this.$table.innerHTML = '';
}
async insertItems(page) {
const html = await this.getItemsByPage(page);
this.$table.insertAdjacentHTML('afterbegin', html);
} }
async getItemsByPage(page) { async getItemsByPage(page) {

View File

@ -1,41 +1,20 @@
import { Component } from "../core/component"; import { Component } from "../core/component";
import { apiService } from "../services/api.service";
export class PaginationComponent extends Component { export class PaginationComponent extends Component {
constructor(id, {items}) { constructor(id, {loader}) {
super(id); super(id);
this.limit = 5; this.loader = loader;
this.items = items;
} }
async init() { // вставляем кнопки со страницами и назначаем ивент
await this.insertPages(); initialize(pages, insertTo, request) {
this.insertButtons(pages);
this.$pages = this.$el.querySelectorAll('li'); this.$pages = this.$el.querySelectorAll('li');
this.$el.addEventListener('click', this.buttonHandler.bind(this)); this.$el.onclick = (e) => this.buttonHandler(e, insertTo, request);
this.moveTo(1, insertTo, request); // показываем первую страницу
this.$el.querySelector('li').nextElementSibling.classList.add('active'); 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() { removeActive() {
this.$pages.forEach(li => li.classList.remove('active')); this.$pages.forEach(li => li.classList.remove('active'));
} }
@ -44,40 +23,53 @@ export class PaginationComponent extends Component {
li.forEach(li => {const page = parseInt(li.querySelector('a').dataset.move);page === value ? li.classList.add('active') : false;}); li.forEach(li => {const page = parseInt(li.querySelector('a').dataset.move);page === value ? li.classList.add('active') : false;});
} }
movePrev(value, li) { buttonHandler(e, insertTo, request) {
if (value === 1) { e.preventDefault();
return 0; if (e.target.dataset.move) {
} else { const page = parseInt(e.target.dataset.move),
--value; target = e.target.parentNode;
this.removeActive(); this.removeActive();
this.setActive(li, value); target.classList.add('active');
this.updatePage(value); this.moveTo(page, insertTo, request);
this.itemsInit(value); } 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, insertTo, request) : this.moveNext(page, this.$pages, insertTo, request);
} }
} }
moveTo(value) { movePrev(page, li, insertTo, request) {
this.updatePage(value); if (page === 1) return 0; else {
this.itemsInit(value); --page;
this.removeActive();
this.setActive(li, page);
this.moveTo(page, insertTo, request);
}
} }
moveNext(value, li) { // выполняем запрос на сервер и выводим на данные
async moveTo(page, insertTo, request) {
this.$el.setAttribute('data-page', page);
insertTo.innerHTML = '';
this.loader.show();
insertTo.insertAdjacentHTML('afterbegin', await request(page));
this.loader.hide();
}
moveNext(page, li, insertTo, request) {
const length = this.$pages.length - 2; const length = this.$pages.length - 2;
if (value === length) { if (page === length) return 0; else {
return 0; ++page;
} else {
++value;
this.removeActive(); this.removeActive();
this.setActive(li, value); this.setActive(li, page);
this.updatePage(value); this.moveTo(page, insertTo, request);
this.itemsInit(value);
} }
} }
async insertPages() { insertButtons(pages) {
const pages = await apiService.getItems(), const count = Math.ceil(pages / 5);
count = pages.length / this.limit;
let html = ''; let html = '';
// назад // назад
@ -92,11 +84,4 @@ export class PaginationComponent extends Component {
html += '<li><a class="disabled" href="#" data-type="next"><i class="material-icons">chevron_right</i></a></li>'; html += '<li><a class="disabled" href="#" data-type="next"><i class="material-icons">chevron_right</i></a></li>';
this.$el.insertAdjacentHTML('afterbegin', html); this.$el.insertAdjacentHTML('afterbegin', html);
} }
// определяем методы для инициализации наших компонентов
itemsInit(value) {
this.items.onShow();
this.items.insertItems(value);
this.items.onHide();
}
} }

View File

@ -32,7 +32,7 @@ export class MaterializeConfig {
document.querySelector('#type') ? M.textareaAutoResize(document.querySelector('#type')) : false document.querySelector('#type') ? M.textareaAutoResize(document.querySelector('#type')) : false
M.updateTextFields(); M.updateTextFields();
// Окраска li по нажатию // окраска li по нажатию
if (document.querySelector('#currentPage')) { if (document.querySelector('#currentPage')) {
const currentPage = document.querySelector('#currentPage').dataset.current; const currentPage = document.querySelector('#currentPage').dataset.current;
const pages = Array.from(document.querySelectorAll('.collapsible li')); const pages = Array.from(document.querySelectorAll('.collapsible li'));

View File

@ -6,9 +6,9 @@ import { LoaderComponent } from "./components/loader.component.js";
import { PaginationComponent } from "./components/pagination.component.js"; import { PaginationComponent } from "./components/pagination.component.js";
const loader = new LoaderComponent('loader'); const loader = new LoaderComponent('loader');
const pagination = new PaginationComponent('pagination', {loader});
const categories = new CategoriesComponent('categories'); const categories = new CategoriesComponent('categories');
const items = new ItemsComponent('items', {loader}); const items = new ItemsComponent('items', {pagination});
const pagination = new PaginationComponent('pagination', {items});
const editCategory = new editCategoryModal('editCategory', 'edit', 'editCategoryClose'); const editCategory = new editCategoryModal('editCategory', 'edit', 'editCategoryClose');
const materialize = new MaterializeConfig(); const materialize = new MaterializeConfig();
console.log('Control-Panel v1.0.0'); console.log('Control-Panel v1.0.0');