菜单
菜单
文章目录
  1. 1. 一个Backbone项目中使用的简单组件
    1. 1.1. Model
    2. 1.2. View
    3. 1.3. 完整代码

backbone paginator

一个Backbone项目中使用的简单组件

Model

分页最基本的需要4个参数,size,page,total已经pageChange. 这里的showPageA表示最多显示的按钮个数,
pageChange的函数在生成实力时传入.

1
2
3
4
5
6
7
8
var PanigatorModel = Backbone.Model.extend({
defaults: {
size: 5,
currentPage: 1,//第一页从1开始不是0
showPageA: 5,//最多显示5个
total: 10
}
})

View

改变参数时变化totalPage和需要显示的按钮showList.
点击按钮时触发pageChange(请求数据)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
var PanigatorView = Backbone.View.extend({
el: '.pager',
events: {
'click .pageA': 'changePage'
},
template: _.template($('#paginator').html()),
initialize: function () {
var self = this;
self.setTotalPage();
self.model.bind('change', function () {
self.setTotalPage();
});
},
changePage: function (ev) {
if ($(ev.currentTarget).hasClass('disable')||$(ev.currentTarget).hasClass('pageActive')){
return false;
}
this.model.attributes.pageChange($(ev.currentTarget).data('index'))
},
render: function (page) {
this.$el.html(this.template(this.model.toJSON()));
},
setTotalPage: function () {
var showList = [];
var totalPage = Math.floor((this.model.get('total') - 1) / this.model.get('size')) + 1;
var currentPage = this.model.get('currentPage');
var showPageA = this.model.get('showPageA');
if (totalPage <= showPageA || currentPage < Math.floor(showPageA / 2) + 1) {
for (var i = 1; i <= totalPage && showList.length <= showPageA - 1; i++) {
showList.push(i)
}
} else if (currentPage > totalPage - Math.ceil(showPageA / 2)) {
for (var i = totalPage; showList.length <= showPageA - 1; i--) {
showList.unshift(i)
}
} else {
for (var i = currentPage - Math.floor(showPageA / 2); i <= currentPage + Math.ceil(showPageA / 2) - 1 && showList.length <= showPageA - 1; i++) {
showList.push(i)
}
}
this.model.set('totalPage', totalPage);
this.model.set('showList', showList);
}
});

完整代码

https://github.com/caolinjian/express-myapp 这是一个简单的express应用在node版本0.10下运行
$ node bin/www

然后打开 http://127.0.0.1:4000/html/backbone-pager.html 对应的html文件在
https://github.com/caolinjian/express-myapp/blob/master/public/html/backbone-pager.html
banckbone-paginator的组件在 https://github.com/caolinjian/express-myapp/blob/master/public/javascripts/backbone-paginator.js