はじめに
前回の続きです。
1つのTodoを表すViewのコードです。
var TodoView = Backbone.View.extend({ tagName: "li", template: _.template($('#item-template').html()), events: { "click .toggle": "toggleDone", "dblclick .view": "edit", "click a.destroy": "clear", "keypress .edit": "updateOnEnter", "blur .edit": "close" }, initialize: function(){ this.listenTo(this.model, 'change', this.render); this.listenTo(this.model, 'destroy', this.remove); }, render: function(){ this.$el.html(this.template(this.model.toJSON())); }, toggleDone: function(){ this.model.toggle(); }, edit: function(){ this.$el.addClass("editing"); this.input.focus(); }, close: function(){ var value = this.input.val(); if(!value){ this.clear(); } else{ this.model.save({title: value}); this.$el.removeClass("editing"); } }, updateOnEnter: function(e){ if(e.keyCode == 13) this.close(); }, clear: function(){ this.model.destroy(); } });
コード解説
tagName: “li”,
これがliタグのビューであることを宣言します。この時点では画面上にこのビューによるliタグは存在しません。インスタンス化してrender結果を画面のDOMツリーに追加することで描画されます。
template: _.template($(‘#item-template’).html()),
Underscore.jsのtemplateメソッドです。scriptタグ内に記述してあるHTML文字列をテンプレートとして利用します。
events: {
“click .toggle”: “toggleDone”,
“dblclick .view”: “edit”,
“click a.destroy”: “clear”,
“keypress .edit”: “updateOnEnter”,
“blur .edit”: “close”
},
イベント定義です。
initialize: function(){
this.listenTo(this.model, ‘change’, this.render);
this.listenTo(this.model, ‘destroy’, this.remove);
},
モデルのイベントをサブスクリプションします。モデルが変更されれば、renderメソッドが実行されます。
render: function(){
this.$el.html(this.template(this.model.toJSON()));
},
テンプレートの引数にモデルを与えてHTMLをメモリ上に構築します。
toggleDone: function(){
this.model.toggle();
},
このビューに関連付いているモデルのtoggleメソッドを呼ぶ。
edit: function(){
this.$el.addClass(“editing”);
this.input.focus();
},
editingクラスを追加してフォーカスを当てる。(Todoを編集状態にする。)
close: function(){
var value = this.input.val();
if(!value){
this.clear();
}
else{
this.model.save({title: value});
this.$el.removeClass(“editing”);
}
},
テキストボックスに入力がなければclearメソッドを呼ぶ。(モデルは削除されます。)入力があれば、モデルを保存し、編集状態を抜けます。
updateOnEnter: function(e){
if(e.keyCode == 13) this.close();
},
Enterキーが押されたとき、closeメソッドを呼びます。
clear: function(){
this.model.destroy();
}
このビューに関連付いているモデルを削除します。
次は今まで定義したモデル、コレクション、ビューを使用してアプリケーションを構築します。