1. 封装分页组件, 不须要在内部页面保护公共数据,只须要在公共数据局部保护该分页器实例自身即可
2. 所有的数据都在外部实现计算,存储, 多个分页器实例都是新的单例 (工厂模式),都是独立的存在,不必放心分页器之间的数据粘连
次要用了 setter getter 以及事件侦听抛发机制, 及时的实现数据视图的双向通信
1. 属性写在办法里面是 ES7 的写法,而 webpack 打包时, 必须要装 babel 的 plugin 能力打包, 否则出错。所以这里长期的解决方案是在构造函数内及 init 函数内创立类中须要调用的属性
2. 如果有其余需要, 则内部能够操作扭转 pageSize,total,currentPage 三个属性的扭转
export default class paginations extends EventTarget{constructor(_eventType) {// 初始化时须要申明自定义事件类型,指定数据抛发的指向对象
super();
this.elem = this.createElem();// 放分页器的容器
this.elem.className="paganitionCon"
this.elem.addEventListener("click", (e) => this.clickHandler(e));
this.eventType = _eventType;
this.init();// 初始化款式, 没有数据
this.render();
this.hightlight();}
init() {
this._pageSize = 3;// 每页显示条目个数
this._total = 0;// 总条目数
this._currentPage = 1;// 当前页数
this.pageCount = Math.ceil(this.total / this.pageSize);// 须要渲染的页数
}
createElem(){if(this.elem) return this.elem;
let div=document.createElement("div");
return div;
}
appendTo(parent){if(typeof parent==="string")parent=document.querySelector(parent);
parent.appendChild(this.elem);
}
set total(value) {// 当总条数扭转时,total 扭转
this._total = value;
this.pageCount = Math.ceil(this.total / this.pageSize);
this.render();
this.hightlight();}
get total() {return this._total;}
set pageSize(value) {// 每页显示条目个数扭转时, 触发扭转
this._pageSize = value;
this.pageCount = Math.ceil(this.total / this.pageSize);
this.render();
this.hightlight();}
get pageSize() {return this._pageSize;}
set currentPage(value) {
this._currentPage = value;
this.render();
this.hightlight();}
get currentPage() {return this._currentPage;}
render() {
this.elem.innerHTML = "";
this.elem.innerHTML = `
<ul class="pagination pagination-sm no-margin pull-right" id="paginationModule">
<li><a href="javascript:;" class="left">«</a></li>
${(function (pageCount) {var arr = [];
for (let i = 1; i <= pageCount; i++){arr.push("<li><a href='javascript:void(0)'>" + i + "</a></li>");
}
return arr.join("");
})(this.pageCount)}
<li><a href="javascript:;" class="right">»</a></li>
</ul>`;
}
clickHandler(e) {if (e.target.nodeName !== "A") return;
switch (e.target.className) {
case "":
this.currentPage = Number(e.target.textContent);
break;
case "left":
if (this.currentPage > 1) this.currentPage--;
else this.currentPage = 1;
break;
case "right":
if (this.currentPage < this.pageCount) this.currentPage++;
else this.currentPage = this.pageCount;
break;
}
this.dispatch(this.currentPage);
}
hightlight() {this.liArr = this.elem.querySelectorAll("li");// 存储所有的页数对应的 li
if (this.prev) this.prev.className = "";// 给 prev 设置为 active,prev 是指须要高亮的页数
if (this.currentPage) {// 当数据全副删除完,则无高亮成果
this.prev = this.liArr[this.currentPage];
this.prev.className = "active";
}
}
dispatch(currentPage) {let evt = new Event(this.eventType);
evt.data = {currentPage}
this.dispatchEvent(evt);
}
}