パークのソフトウエア開発者ブログ|ICT技術(Java・Android・iPhone・C・Ruby)なら株式会社パークにお任せください -9ページ目

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

開発の解決方法や新しい手法の情報を、パークのエンジニアが提供します。パークのエンジニアが必要な場合は、ぜひお気軽にお問い合わせ下さい。 株式会社パーク:http://www.pa-rk.co.jp/

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

今回は、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-item">
<th>
<input class="cls_radio_button" type="radio" name="item">
</th>
<td><%= data.name %></td>
</script>


テーブルデータ1件分のテンプレート template-user-table-item を作成します。
ラジオボタンのスタイルクラス名は cls_radio_button と定義します。

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


var UserCollection = Backbone.Collection.extend({
model : UserModel,
removeSelectedModel : function() {
this.remove(this.selectedModel); // (5)
},
selectedModel : null
});

var UserTableView = Backbone.View.extend({
name : 'UserTableView',
events : {
'click #id_button_delete' : 'onClickDeleteButton' // (3)
},
initialize : function(args) {
this.collection = args.collection;
this.listenTo(this.collection, 'add', this.onAdd);
this.listenTo(this.collection, 'remove', this.onRemove);
this.compiledTemplate = _.template($('#template-user-table').text());
},
render : function() {
var tempData = {
'header' : {
'name' : '名前'
},
'label' : {
'deleteButton' : '削除'
}
};
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,
'collection' : this.collection
})).render().el);
}, this);
},
onAdd : function() {
console.log(this.name + '#onAdd');
this.renderItem();
},
onRemove : function() {
console.log(this.name + '#onRemove');
this.renderItem();
},
onClickDeleteButton : function(event) {
console.log(this.name + '#onClickDeleteButton');
this.collection.removeSelectedModel(); // (4)
}
});

var UserTableItemView = Backbone.View.extend({
name : 'UserTableItemView',
tagName : 'tr',
events : {
'click .cls_radio_button' : 'onClickRadioButton' // (1)
},
initialize : function(args) {
this.model = args.model;
this.collection = args.collection;
this.compiledTemplate = _.template($('#template-user-table-item').text());
},
render : function() {
var templateData = {
'data' : this.model.toJSON()
};
this.$el.append(this.compiledTemplate(templateData));
return this;
},
onClickRadioButton : function(event) {
console.log(this.name + '#onClickRadioButton:' + event.target.checked);
this.collection.selectedModel = this.model; // (2)
}
});


(1) ラジオボタンのクリックイベントを監視します。
(2) ラジオボタンを押下すると、コレクションのプロパティ selectedModel にモデルを設定します。押下される度に、押下対象のモデルを設定します。
(3) 削除ボタンのクリックイベントを監視します。
(4) 削除ボタンを押下すると、コレクションの removeSelectedModel 関数を呼びます。
(5) コレクションの remove 関数で、selectedModel に設定されているモデルを削除します。



■ラジオボタンのテーブル (ソート・複数のヘッダー)

先ほどのラジオボタンのテーブルに
複数のヘッダーとソート機能を追加します。
しかし、そのまま追加すると、ソートの再描画時にラジオボタンが消去されてしまうため、
再描画時に、ラジオボタンの表示判定を行います。

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

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


var UserCollection = Backbone.Collection.extend({
model : UserModel,
sortAttribute : '',
sortDirection : 1,
initialize : function() {
var that = this;
this.sortComparators = {
'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) {
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) {
return model.get(this.sortAttribute) * this.sortDirection;
},
removeSelectedModel : function() {
this.remove(this.selectedModel);
},
selectModel : function(model) {
_.each(this.models, function(model) { // (2)
model.isSelected = false;
}, this);
model.isSelected = true;
this.selectedModel = model;
}
});
var UserTableItemView = Backbone.View.extend({
name : 'UserTableItemView',
tagName : 'tr',
events : {
'click .cls_radio_button' : 'onClickRadioButton'
},
initialize : function(args) {
this.model = args.model;
this.collection = args.collection;
this.compiledTemplate = _.template($('#template-user-table-item').text());
},
render : function() {
var templateData = {
'data' : this.model.toJSON()
};
this.$el.append(this.compiledTemplate(templateData));
if (this.model.isSelected) { // (3)
this.$el.find('.cls_checkbox').prop('checked', true)
}
return this;
},
onClickRadioButton: function(event) {
console.log(this.name + '#onClickRadioButton:' + event.target.checked);
this.collection.selectModel(this.model); // (1)
}
});


(1) ラジオボタンを押下すると、モデルを引数にして、コレクションの selectModel 関数を呼び出します。
(2) モデルの選択フラグ isSelected を全て false にしてから、現在選択されているモデルの isSelected を true にします。また、selectedModel にモデルを設定します。
(3) テーブルデータの描画時に、モデルの isSelected を判定して、選択中であれば、ラジオボタンにチェックを入れます。

以上です。



□過去の記事

Backbone.js入門その11「ソートテーブルを作る」
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つの要素を作る」
こんばんは。ゆんぼうです。

今回は、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つの要素を作る」

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

前回までは、登録ボタンを押すと、リストが追加されていきました。
今回は、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/



■ヘッダーが1つのテーブル

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

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

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


<script type="text/template" id="template-user-table">
<table class="cls_table">
<thead>
<tr>
<th><%= header.name %></th>
</tr>
</thead>
<tbody id="id_tbody">
</tbody>
</table>
</script>
<script type="text/template" id="template-user-table-item">
<td><%= data.name %></td>
</script>


テーブル用のテンプレートを用意します。
テンプレートID template-user-table がテーブルのヘッダー、
template-user-table-item がテーブルのデータとなります。

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


var UserTableView = Backbone.View.extend({
name : 'UserTableView',
initialize : function(args) {
this.collection = args.collection;
this.listenTo(this.collection, 'add', this.onAdd);
this.compiledTemplate = _.template($('#template-user-table').text());
},
render : function() {
var tempData = {
'header' : {
'name' : '名前'
}
};
this.$el.append(this.compiledTemplate(tempData)); // (1)
return this;
},
renderItem : function() {
this.$el.find('#id_tbody').html('');
_.each(this.collection.models, function(model) { // (3)
this.$el.find('#id_tbody').append((new UserTableItemView({
'model' : model
})).render().el);
}, this);
},
onAdd : function() {
console.log(this.name + '#onAdd');
this.renderItem(); // (2)
}
});


UserRegisterView は前回と同じ内容です。
今回は、テーブル全体を現す UserTableView とテーブルの1件分のデータを表す UserTableItemView を新たに作成します。

(1) UserTableView でテーブルのヘッダーを描画します。
(2)(3) 登録ボタンを押下すると、UserCollection にデータが追加され、add イベントが発火されます。onAdd 関数が呼び出され、renderItem 関数でテーブルデータを描画します。



■ヘッダーが複数のテーブル

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

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

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


<script type="text/template" id="template-user-table">
<table class="cls_table">
<thead>
<tr>
<th><%= header.name %></th>
<th><%= header.age %></th>
<th><%= header.gender %></th>
<th><%= header.blood %></th>
<th><%= header.mailAddress %></th>
</tr>
</thead>
<tbody id="id_tbody">
</tbody>
</table>
</script>
<script type="text/template" id="template-user-table-item">
<td><%= data.name %></td>
<td><%= data.age %></td>
<td><%= data.gender %></td>
<td><%= data.blood %></td>
<td><%= data.mailAddress %></td>
</script>


テンプレートにそれぞれ「年齢」「性別「血液型」「メールアドレス」を追加します。
また、UserModel にも同様に追加します。

以上です。



□過去の記事

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つの要素を作る」
こんばんは。ゆんぼうです。

今回は、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-list-item">
<%= label.name %>
<input type="button" class="cls_button_detail" value="<%= label.detailButton %>">
<input type="button" class="cls_button_delete" value="<%= label.deleteButton %>">
</script>
<script type="text/template" id="template-user-register">
<label for="id_input_name"><%= label.name %></label>
<input id="id_input_name" type="text">
<br>
<label for="id_input_age"><%= label.age %></label>
<input id="id_input_age" type="number" min="0" max="99">
<br>
<label for="id_select_gender"><%= label.gender %></label>
<select id="id_select_gender">
<option><%= label.male %></option>
<option><%= label.female %></option>
</select>
<br>
<label for="id_select_blood"><%= label.blood %></label>
<select id="id_select_blood">
<option>A</option>
<option>B</option>
<option>O</option>
<option>AB</option>
</select>
<br>
<label for="id_input_mail"><%= label.mail %></label>
<input id="id_input_mail" type="text">
<br>
<input id="id_button_regist" type="button" value="<%= label.registButton %>">
<hr>
</script>


テンプレートID template-user-list-item はリスト1件分のテンプレートです。
削除ボタンと詳細ボタンを表示します。

template-user-register が登録画面のテンプレートです。
名前、年齢、性別、血液型、メールアドレスの入力項目を表示します。

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


var UserListItemView = Backbone.View.extend({
name : 'UserListItemView',
tagName : 'li',
events : {
'click .cls_button_detail' : 'onClickDetailButton',
'click .cls_button_delete' : 'onClickDeleteButton'
},
initialize : function(args) {
this.model = args.model;
this.collection = args.collection
this.compiledTemplate = _.template($('#template-user-list-item').text());
},
render : function() {
var templateData = {
'label' : {
'name' : this.model.get('name'),
'detailButton' : '詳細',
'deleteButton' : '削除'
}
};
this.$el.append(this.compiledTemplate(templateData));
return this;
},
onClickDetailButton : function() {
console.log(this.name + '#onClickDetailButton');
var message = '';
message += '\n名前 : ' + this.model.get('name'); // (1)
message += '\n年齢 : ' + this.model.get('age');
message += '\n性別 : ' + this.model.get('gender');
message += '\n血液型 : ' + this.model.get('blood');
message += '\nメールアドレス : ' + this.model.get('mailAddress');
alert(message); // (2)
},
onClickDeleteButton : function() {
console.log(this.name + '#onClickDeleteButton');
this.collection.remove(this.model);
}
});


(1) model.get で指定したプロパティを取得することができます。
(2) アラートに生成した文字列を渡しています。

以上です。



□過去の記事

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つの要素を作る」
こんばんは。ゆんぼうです。

今回は、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-list-item">
<%= label.name %>
<input type="button" class="cls_button_delete" value="<%= label.deleteButton %>">
</script>
<script type="text/template" id="template-user-register">
<label for="id_input_name"><%= label.name %></label>
<input id="id_input_name" type="text">
<br>
<input id="id_button_regist" type="button" value="<%= label.registButton %>">
<hr>
</script>


テンプレートID template-user-list-item はリスト1件分のテンプレート、
template-user-register が登録画面のテンプレートです。

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


var UserListView = Backbone.View.extend({
name : 'UserListView',
tagName : 'ul',
initialize : function(args) {
this.collection = args.collection;
this.listenTo(this.collection, 'add', this.onAdd);
this.listenTo(this.collection, 'remove', this.onRemove);
},
render : function() {
this.$el.html('');
_.each(this.collection.models, function(model) {
this.$el.append((new UserListItemView({
'model' : model,
'collection' : this.collection
})).render().el);
}, this);
return this;
},
onAdd : function() {
console.log(this.name + '#onAdd');
this.render();
},
onRemove : function() { // (3)
console.log(this.name + '#onRemove');
this.render();
}
});

var UserListItemView = Backbone.View.extend({
name : 'UserListItemView',
tagName : 'li',
events : {
'click .cls_button_delete' : 'onClickDeleteButton'
},
initialize : function(args) {
this.model = args.model;
this.collection = args.collection;
this.compiledTemplate = _.template($('#template-user-list-item').text());
},
render : function() {
var templateData = {
'label' : {
'name' : this.model.get('name'),
'deleteButton' : '削除'
}
};
this.$el.append(this.compiledTemplate(templateData)); // (1)
return this;
},
onClickDeleteButton : function() {
console.log(this.name + '#onClickDeleteButton');
this.collection.remove(this.model); // (2)
}
});


(1) リスト1件分を表す UserListItemView に削除ボタンのテンプレートを追加します。
(2) 削除ボタンを押下したときに、collection.remove で collection から該当の model を削除します。
(3) collection には既に model が削除されています。remove イベントが発火されたときに、render 関数を呼び出しリストを再描画します。その結果、削除された後のリストが表示されます。



■チェックボックスリストと削除ボタン

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

先ほどは、リスト毎に削除しておりましたが、
ここでは、チェックボックスにチェックがあるリストを纏めて削除するものを作成します。

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


<script type="text/template" id="template-user-list">
<input id="id_button_delete" type="button" value="<%= label.deleteButton %>">
<hr>
<ul id="id_ul_user_list"></ul>
</script>
<script type="text/template" id="template-user-list-item">
<input class="cls_checkbox" type="checkbox"> <%= label.name %>
</script>
<script type="text/template" id="template-user-register">
<label for="id_input_name"><%= label.name %></label>
<input id="id_input_name" type="text">
<br>
<input id="id_button_regist" type="button" value="<%= label.registButton %>">
<hr>
</script>


テンプレートID template-user-list はリスト全体のテンプレートです。

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


var UserModel = Backbone.Model.extend({
defaults : {
'name' : ''
},
isSelected : false, // (2)
validate : function(attribuite) {
if (_.isEmpty(attribuite.name)) {
return "名前が入力されていません";
}
}
});

var UserCollection = Backbone.Collection.extend({
model : UserModel,
removeSelectedModel : function() { // (5)
var selectedCollection = this.models.filter(function(model) {
return model.isSelected;
});
this.remove(selectedCollection);
}
});

var UserListView = Backbone.View.extend({
name : 'UserListView',
events : {
'click #id_button_delete' : 'onClickDeleteButton'
},
initialize : function(args) {
this.collection = args.collection;
this.listenTo(this.collection, 'add', this.onAdd);
this.listenTo(this.collection, 'remove', this.onRemove);
this.compiledTemplate = _.template($('#template-user-list').text());
},
render : function() {
var templateData = {
'label' : {
'deleteButton' : '削除'
}
};
this.$el.append(this.compiledTemplate(templateData)) // (1)
return this;
},
renderItem : function() {
this.$el.find('#id_ul_user_list').html('');
_.each(this.collection.models, function(model) {
this.$el.find('#id_ul_user_list').append((new UserListItemView({
'model' : model,
'collection' : this.collection
})).render().el);
}, this);
},
onAdd : function() {
console.log(this.name + '#onAdd');
this.renderItem();
},
onRemove : function() {
console.log(this.name + '#onRemove');
this.renderItem(); // (6)
},
onClickDeleteButton : function() {
console.log(this.name + '#onClickDeleteButton');
this.collection.removeSelectedModel(); // (4)
}
});

var UserListItemView = Backbone.View.extend({
name : 'UserListItemView',
tagName : 'li',
events : {
'click .cls_checkbox' : 'onClickCheckBox'
},
initialize : function(args) {
this.model = args.model;
this.collection = args.collection;
this.compiledTemplate = _.template($('#template-user-list-item').text());
},
render : function() {
var templateData = {
'label' : {
'name' : this.model.get('name')
}
};
this.$el.append(this.compiledTemplate(templateData));
return this;
},
onClickCheckBox : function(event) {
console.log(this.name + '#onClickCheckBox');
this.model.isSelected = event.target.checked; // (3)
}
});


(1) リスト全体を表す UserListView に削除ボタンのテンプレートを追加します。
(2) model に isSelected プロパティを追加します。
(3) チェックボックスをON/OFFすると、model の isSelected にチェック状態を代入します。
(4) 削除ボタンを押下すると、collection の removeSelectedModel 関数を実行します。
(5) isSelected=true である model を削除します。
(6) remove イベントが発火されたときに、render 関数を呼び出しリストを再描画します。

以上です。



□過去の記事

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つの要素を作る」