コンテンツへスキップ

hifiveのデータグリッドライブラリを使いこなす(8)「ページネーションする」

by : 2017/04/27

前回の表示件数の変更に続いて、ページネーションの追加方法です。ページネーションができると見たいデータだけを絞り込んで表示できます。

実際に動いているデモはこちらにあります。動かしているところは下記の画像になります。

HTMLにページネーション情報を追加する

まずHTMLにページを移動するボタンと現在、トータルのページ数を表示するHTMLを追加します。


<div class="row">
<div class="col-md-12">
<button id="prev">&lt;</button>
<span id="page"></span>/
<span id="total_page"></span>
<button id="next">&gt;</button>
</div>
</div>

view raw

index.html

hosted with ❤ by GitHub

ページネーション情報を表示する

実際にページネーションを表示するJavaScriptは次のようになります。1ページ目を表示している時には前のページに移動するボタンを無効にして、最後のページまで移動した時には次のページに移動しないようにします。使うのは this._dataSearcher.getCurrentPage() と this._dataSearcher.getTotalPages() になります。


update_page: function() {
var currentPage = this._dataSearcher.getCurrentPage();
$("#prev").attr('disabled', currentPage == 1);
this.$find('#page').text(currentPage);
var totalPage = this._dataSearcher.getTotalPages();
$("#next").attr('disabled', currentPage == totalPage);
this.$find('#total_page').text(totalPage);
},

view raw

index.js

hosted with ❤ by GitHub

後はこの update_page を適時呼び出します。


datagrid.util.delay(1000, this.own(function() {
this._gridController.search({});
this.update_page(); // 追加
}));

view raw

index.js

hosted with ❤ by GitHub

表示件数を変更した際にも呼び出します。


'#paging change': function(context, $el) {
context.event.preventDefault();
this._dataSearcher.setPageSize(parseInt($el.val()));
this.update_page();
},

view raw

index.js

hosted with ❤ by GitHub

ページ移動のイベントを追加する

最後にページを移動する際の処理を追加します。これは this._dataSearcher.movePage を使います。まず前のページへの移動です。


'#prev click': function(context, $el) {
this._dataSearcher.movePage(this._dataSearcher.getCurrentPage() 1);
this.update_page();
},

view raw

index.js

hosted with ❤ by GitHub

次に次のページへの移動です。


'#next click': function(context, $el) {
this._dataSearcher.movePage(this._dataSearcher.getCurrentPage() + 1);
this.update_page();
}

view raw

index.js

hosted with ❤ by GitHub

これでページネーション機能が実装されました。


例えば最初のページへの移動であれば this._dataSearcher.movePage に 1 を与えるだけですし、最後のページへの移動は this._dataSearcher.getTotalPages() を与えるだけです。ごく簡単にグリッドに対してページネーションが使えるようになります。

実際に動いているデモはこちらにあります。ぜひ試してみてください。

banner_02

From → hifive

コメントは受け付けていません。

%d人のブロガーが「いいね」をつけました。