Quantcast
Channel: パークのソフトウエア開発者ブログ|ICT技術(Java・Android・iPhone・C・Ruby)なら株式会社パークにお任せください
Viewing all articles
Browse latest Browse all 138

Backbone.js入門その11「ソートテーブルを作る」

$
0
0

こんばんは。ゆんぼうです。

今回は、Backbone.jsを使用して、ヘッダーを押す度にソートを行うテーブルを作成します。

今回使用する環境は下記の通りです。

Webブラウザ
・Mozilla Firefox (v34.05) https://www.mozilla.org/ja/firefox/new/
・FireBug (v2.0.7) https://addons.mozilla.org/ja/firefox/addon/firebug/

JavaScriptライブラリ
・Backbone.js (v1.1.2) http://backbonejs.org/
・Underscore.js (v1.7.0) http://underscorejs.org/
・jQuery (v2.1.1) http://jquery.com/



■数値のソート

【デモはこちら】
【ソースファイルはこちら】

「年齢」ヘッダーを持つテーブルと登録ボタンを作成します。
年齢のテキストボックスに入力して、このボタンを押下すると、
テーブルに年齢が追加されます。
さらに、テーブルのヘッダーを押下するたびに、ソートが行われます。


index.html のhead に下記の内容を記述します。


<script type="text/template" id="template-user-table">
<table class="cls_table">
<thead>
<tr>
<th><a href="javascript:void(0)" class="cls_header" name="age"><%= header.age %><span class="cls_sort_icon"></span></a></th>
</tr>
</thead>
<tbody id="id_tbody">
</tbody>
</table>
</script>
<script type="text/template" id="template-user-table-item">
<td><%= data.age %></td>
</script>


テーブルのヘッダーとデータのテンプレートを作成します。
前回と異なる点は、ヘッダーにリンクを追加しています。

main.js に下記の内容を記述します。


var UserCollection = Backbone.Collection.extend({
model : UserModel,
sortAttribute : '',
sortDirection : 1,
sortToggle : function(attribute) {
this.sortDirection *= -1; // (3)
this.sortAttribute = attribute;
this.sort(); // (4)
},
comparator : function(model) {
return model.get(this.sortAttribute) * this.sortDirection; // (5)
}
});

var UserTableView = Backbone.View.extend({
name : 'UserTableView',
events : {
'click .cls_header' : 'onClickHeader'
},
initialize : function(args) {
this.collection = args.collection;
this.listenTo(this.collection, 'add', this.onAdd);
this.listenTo(this.collection, 'sort', this.onSort);
this.compiledTemplate = _.template($('#template-user-table').text());
this.currentHeader = null;
},
render : function() {
var tempData = {
'header' : {
'age' : '年齢'
}
};
this.$el.append(this.compiledTemplate(tempData));
return this;
},
renderItem : function() {
this.$el.find('#id_tbody').html('');
_.each(this.collection.models, function(model) {
this.$el.find('#id_tbody').append((new UserTableItemView({
'model' : model
})).render().el);
}, this);
},
renderClearSortIcon : function() {
_.each([ 'cls_sort_up', 'cls_sort_down' ], function(sortClass) {
this.$el.find("a[name='" + this.collection.sortAttribute + "'] span").removeClass(sortClass);
}, this);
},
renderSortIcon : function() {
var sortClass = null;
if (this.collection.sortDirection == 1) {
sortClass = 'cls_sort_up';
} else {
sortClass = 'cls_sort_down';
}
this.$el.find("a[name='" + this.collection.sortAttribute + "'] span").addClass(sortClass);
},
onAdd : function() {
console.log(this.name + '#onAdd');
this.renderItem();
},
onSort : function() {
console.log(this.name + '#onSort');
this.renderItem(); // (6)
this.renderSortIcon(); // (7)
},
onClickHeader : function(event) {
console.log(this.name + '#onClickHeader');
this.renderClearSortIcon(); // (1)
this.collection.sortToggle(event.target.name); // (2)
}
});


(1) テーブルのヘッダーをクリックすると、ソートの向きを表すソートアイコンを消去します。
(2) event.target.name は、aタグのname属性値「age」を指します。これを引数にして、UserCollection の sortToggle 関数を実行します。
(3) ソートの向きを指定します。関数が実行する度にソートの向きが逆になります。
(4) sort 関数で UserCollection のソートを実行します。
(5) sort 関数の内部で使用する比較関数 comparator を作成します。comparator の引数は、UserModel になります。UserModel から取り出したデータがソートされます。[+]は昇順、[-]は降順になります。
(6) ソートを実行すると、「sort」 イベントが発火されます。sort イベントが発火されると、テーブルのデータを再描画します。
(7) ソートアイコンを描画します。



■文字列のソート

【デモはこちら】
【ソースファイルはこちら】

さきほど作成したテーブルを
「年齢」から「名前」に変更します。

main.js に下記の内容を記述します。


var UserCollection = Backbone.Collection.extend({
model : UserModel,
sortAttribute : '',
sortDirection : 1,
sortToggle : function(attribute) {
this.sortDirection *= -1;
this.sortAttribute = attribute;
this.sort();
},
comparator : function(a, b) { // (1)
var a = a.get(this.sortAttribute), b = b.get(this.sortAttribute);
if (a == b) {
return 0;
}
if (this.sortDirection == 1) {
return b < a ? 1 : -1;
} else {
return a < b ? 1 : -1;
}
}
})


(1) テーブルのデータが数値から文字列に変更することで、comparator の比較方法も文字列の比較に変更します。文字列は Unicode のコード順に基づいて比較されます。




■数値・文字列の混在ソート

【デモはこちら】
【ソースファイルはこちら】

先ほど作成したテーブルに
「名前」「年齢」「性別「血液型」「メールアドレス」のヘッダーを追加します。

main.js に下記の内容を記述します。


var UserCollection = Backbone.Collection.extend({
model : UserModel,
sortAttribute : '',
sortDirection : 1,
initialize : function() {
var that = this;
this.sortComparators = { // (3)
'name' : that.comparatorString,
'age' : that.comparatorInteger,
'gender' : that.comparatorString,
'blood' : that.comparatorString,
'mailAddress' : that.comparatorString
}
},
sortToggle : function(attribute) {
if (this.sortAttribute == attribute) {
this.sortDirection *= -1;
} else {
this.sortDirection = 1;
}
this.sortAttribute = attribute;
this.comparator = this.sortComparators[attribute];
this.sort();
},
comparatorString : function(a, b) { // (1)
var a = a.get(this.sortAttribute), b = b.get(this.sortAttribute);
if (a == b) {
return 0;
}
if (this.sortDirection == 1) {
return b < a ? 1 : -1;
} else {
return a < b ? 1 : -1;
}
},
comparatorInteger : function(model) { // (2)
return model.get(this.sortAttribute) * this.sortDirection;
}
});


(1)(2) ヘッダーを追加した UserCollection では数値と文字列が混在しているため、数値用と文字列用の比較関数を作成します。
(3) データ毎に、比較関数を定義します。

以上です。



□過去の記事

Backbone.js入門その10「テーブルと登録ボタンを作る」
Backbone.js入門その9「リストと詳細ボタンを作る」
Backbone.js入門その8「リストと削除ボタンを作る」
Backbone.js入門その7「リストと登録ボタンを作る」
Backbone.js入門その6「ModelとCollection」
Backbone.js入門その5「静的HTMLでBackbone.Viewを作る」
Backbone.js入門その4「SuperViewとSubViewのアクセスを作成する」
Backbone.js入門その3「Backbone.ViewでSubViewを作る」
Backbone.js入門その2「Backbone.Viewで複数の要素を作る」
Backbone.js入門その1「Backbone.Viewで1つの要素を作る」


Viewing all articles
Browse latest Browse all 138

Trending Articles