模块代码
pagebar.js
/**
* 分页组件
*/
define(function(require, exports, module) {
var pageBarTpl = require("tpl/pagebar.html"), pageBarTplCom = juicer(pageBarTpl);
var defaultOpts = {};
var PageBar = function(options) {
if (!options.totalCount) {
return;
}
this.container = $(options.container);
this.options = $.extend({}, defaultOpts, options);
this.init();
};
PageBar.prototype = {
constructor : PageBar,
init : function() {
this.initUI();
this.initEvents();
},
initUI : function() {
var opts = this.options;
this.pageCount = parseInt((opts.totalCount + opts.pageSize - 1) / opts.pageSize);
this.container.html(pageBarTplCom.render({
pagecount : this.pageCount
}));
this.pageCount == 1 ? this.container.hide() : this.container.show();
this.currPage = 1;
this.pages = this.container.find(".page-nav");
},
initEvents : function() {
var that = this;
var opts = that.options;
that.container.on("click", "li a", function() {
var index = $(this).data("index"), page;
if (index == "previous") {
index = that.currPage - 1;
} else if (index == "next") {
index = that.currPage + 1;
}
if (index < 1 || index > that.pageCount) {
return;
}
if (index === that.currPage) {
return;
}
for (var i = 0; i < that.pages.length; i++) {
page = $(that.pages[i]);
page.removeClass("active");
if (page.find("a:first-child").data("index") === index) {
page.addClass("active");
}
}
that.currPage = index;
opts.onCallback && opts.onCallback(index);
});
},
destroy : function() {
this.container.off("click", "li a");
}
};
module.exports = PageBar;
});
模板代码
/**
* 分页组件
*/
define(function(require, exports, module){
return '<nav>'+
'<ul class="pagination" style="margin:0 0">'+
' <li class="page-prev"><a href="javascript:void(0);" aria-label="Previous" data-index="previous">'+
' <span aria-hidden="true">«</span>'+
' </a></li>'+
' {@each i in range(1, pagecount+1)}'+
' <li class="page-nav {@if i==1} active{@/if}"><a href="javascript:void(0);" data-index="!{i}">!{i}</a></li>'+
' {@/each}'+
' <li class="page-next"><a href="javascript:void(0);" aria-label="Next" data-index="next">'+
' <span aria-hidden="true">»</span>'+
' </a></li>'+
'</ul>'+
'</nav>';
});
调用代码
initPageBar : function(imgcount) {
var that = this;
var imgdg = $(that.dialog.node);
var opts = that.options;
that.pagebar && that.pagebar.destroy();
if (opts.pageSize >= imgcount) {
$("#img-pagebar").empty();
$("#img-pagebar").hide();
} else {
that.pagebar = new PageBar({
container : "#img-pagebar",
totalCount : imgcount,
pageSize : opts.pageSize,
onCallback : function(index) {
imgdg.find("#img-pagebar").hide();
imgdg.find(".js_loading").show();
that.getImageList({
begin : (index - 1) * opts.pageSize,
count : opts.pageSize
}, function(data) {
var images = data.images;
that.renderImageList(images, that.imgArr);
imgdg.find("#img-pagebar").show();
imgdg.find(".js_loading").hide();
});
imgdg.find(".imgdg-main").scrollTop(0);
}
});
}
},
效果演示