LoginSignup
9
9

More than 5 years have passed since last update.

Ember.jsで高機能なテーブルを表示する

Posted at

Ember Tableというテーブル表示ライブラリを使うことで、高機能なテーブルを表示できます。
遅延読み込みにも対応しており、大量のデータを表示するのに効果を発揮します。(100万行のデータを表示するサンプルは、非常に高速に動作しています。)

(Ember Table)[http://addepar.github.com/ember-table/]

Ember Tableは以下のような機能を持っています。

  • 表示要素の書式をカスタマイズ(金額表示、日付表示などは組み込みで用意されてる)
  • レイティング入力
  • 折れ線グラフ
  • 棒グラフ
  • 合計行表示
  • データをajaxで遅延読み込み
  • ツリーデータの子要素の展開/非表示切り替え

以下表示サンプルのコードです。まずテンプレートです。

<script type="text/x-handlebars" data-template-name="application">
  <div class='presentation-container'>
    {{view Ember.Table.TablesContainer controllerBinding="tableController"}}
  </div>
</script>

Ember.Table.TablesContainer を使って表示します。シンプルですね。

App.TableSimpleExample.TableController = Ember.Table.TableController.extend
  hasHeader: yes 
  hasFooter: no
  numFixedColumns: 0
  numRows: 1000000
  rowHeight: 30

  columns: Ember.computed ->
    columnNames = ['open', 'high', 'low', 'close', 'volume']
    entryColumn = Ember.Table.ColumnDefinition.create
      columnWidth: 100
      headerCellName: 'Entry'
      getCellContent: (row) -> row['index'];
    dateColumn = Ember.Table.ColumnDefinition.create
      columnWidth: 150
      headerCellName: 'Date'
      getCellContent: (row) -> row['date'].toDateString();
    columns= columnNames.map (key, index) ->
      name = key.charAt(0).toUpperCase() + key.slice(1)
      Ember.Table.ColumnDefinition.create
        columnWidth: 100
        headerCellName: name
        getCellContent: (row) -> row[key].toFixed(2)
    columns.unshift(dateColumn)
    columns.unshift(entryColumn)
    columns
  .property()

  content: Ember.computed ->
    App.TableSimpleExample.LazyDataSource.create
      content: new Array(@get('numRows'))
  .property 'numRows'

columnsメソッドは、列の定義を返します。各列の名前、書式、幅を指定しています。
contentメソッドが、データを返します。LazyDataSourceを使って、遅延読み込みを行なっています。
numRowsは項目の数です。1000000行が設定されています。行が表示される段階で実データを取得します。読み込まれます。

最後にLazyDataSourceの定義を見てみましょう。

App.TableSimpleExample.LazyDataSource = Ember.ArrayProxy.extend
  objectAt: (idx) ->
    row  = @get('content')[idx]
    return row if row
    date = new Date();
    date.setDate(date.getDate() + idx)
    row =
      index: idx
      date:  date
      open:  Math.random() * 100 - 50
      high:  Math.random() * 100 - 50
      low:   Math.random() * 100 - 50
      close: Math.random() * 100 - 50
      volume: Math.random() * 1000000
    @get('content')[idx] = row
    row

ここでは外部からデータを読み込んでくることはせず、ランダム値を使ってサンプルデータを生成しています。

このサンプルの実際の動作は、以下のページで確認できます。

Ember Tableには、データをajax経由で動的に読み込んでくるサンプルもあり、遅延読み込みにも対応しています。

大量のデータの表示に耐えうるライブラリだと感じました。

9
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
9