コンテンツへスキップ

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

by : 2017/04/12

業務要件でグリッドを使っているとよくあるページネーション対応。大量のデータを表示する際に、20件ずつ表示するようにして欲しいと言った話を聞いたことは多々あるでしょう。

JavaScriptでページネーションを実現するのは面倒ですが、hifiveのグリッドコントローラを使うと容易に実装できます。

こちらにデモがあります。なお、ベースになるコードは hifiveのデータグリッドライブラリを使いこなす(1)「グリッドの基本形」 になります。

実装すると次のようになります。

HTMLの変更

HTMLではページネーションを操作するためのDOMを用意します。例えば今回は次のようになります。


<div class="col form-inline">
<span id="firstPage">&#8810;</span> &nbsp;
<span id="prevPage">&lt;</span> &nbsp;
<input id="currentPage" type="text"> / <span id="totalPages"></span>ページ&nbsp;
<span id="nextPage">&gt;</span>&nbsp;
<span id="lastPage">&#8811;</span>
</div>

view raw

index.js

hosted with ❤ by GitHub

初期化パラメータの追加

初期化する際に1ページに何件表示するかの指定を行います。今回は10件表示とします。


var initParam = {
searcher: {
type: 'all',
// 以下を追加
paging: {
enable: true,
pageSize: 10
}
},
:

view raw

index.html

hosted with ❤ by GitHub

データサーチャーを用意する

今回は新しくデータサーチャーというプロパティを用意します。これはグリッドコントローラから呼び出せますが、繰り返し使うので取り出しておきます。


var scrollGridController = {
__name: 'datagrid.sample.ScrollGridController',
__meta: {
_gridController: {
rootElement: '#grid'
}
},
_gridController: datagrid.GridController,
_dataSearcher: null, // 追加
:
__ready: function() {
:
this._gridController.activate(dataSource, initParam);
// 以下を追加
this._dataSearcher = this._gridController.getDataSearcher();
:
}

view raw

index.js

hosted with ❤ by GitHub

初期表示処理

グリッドの準備ができたところで現在のページ数やトータルのページ数を表示します。トータルのページ数は this._dataSearcher.getTotalPages() で取得できます。


datagrid.util.delay(1000, this.own(function() {
this._gridController.search({});
// 以下を追加
var totalPages = this._dataSearcher.getTotalPages();
this.$find('#totalPages').text(totalPages);
this._updateCurrentPage();
}));

view raw

index.js

hosted with ❤ by GitHub

ページを切り替える

ページの切り替えは次のように行います。以下は1ページ目への移動です。


this._dataSearcher.movePage(1);

view raw

index.js

hosted with ❤ by GitHub

後は各ページネーション移動の際のイベントで上記メソッドを実行します。以下は次のページへの移動処理の場合です。


'#nextPage click': function(context, $el) {
context.event.preventDefault();
var currentPage = this._dataSearcher.getCurrentPage();
var totalPage = this._dataSearcher.getTotalPages();
if ((currentPage + 1) <= totalPage) {
this._dataSearcher.movePage(currentPage + 1);
this._updateCurrentPage();
}
},

view raw

index.js

hosted with ❤ by GitHub

this._updateCurrentPageはページ番号を表示する処理です。 this._dataSearcher.getCurrentPage() で現在のページ数が表示できます。


_updateCurrentPage: function() {
var currentPage = this._dataSearcher.getCurrentPage();
this.$find('#currentPage').val(currentPage);
}

view raw

index.js

hosted with ❤ by GitHub


ページネーションの処理もhifiveのグリッドコントローラを使えば簡単に実装できます。ぜひデモで確認してください。

グリッドコントローラ – ページネーションデモ

banner_02

From → hifive

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

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