Backbone.js ViewとCollectionの連携
改めてViewとCollectionの連携を復習。
by FiNGAHOLiC
HTML
<script src="http://documentcloud.github.com/underscore/underscore-min.js"></script>
<script src="http://documentcloud.github.com/backbone/backbone-min.js"></script>
<script src="http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js"></script>
<script src="https://getfirebug.com/firebug-lite-debug.js"></script>
JavaScript
(function($, window, document, undefined){
(function(){
// モデルの定義
var Hoge = Backbone.Model.extend({});
// ビューの定義
var HogeView = Backbone.View.extend({
events : {
// DOMのイベントを監視
'click .submit' : 'update'
},
initialize : function(){
_.bindAll(this, 'render', 'remove');
// オブザーバーパターンを利用してモデルのイベントを購読
this.model.bind('change', this.render);
this.model.bind('destroy', this.remove);
},
update : function(){
// changeイベントが発生してrenderが実行される
this.model.set({
foo : 'bar'
});
},
render : function(){
$(this.el).html(_.template($('#template').html(), this.model.attributes));
return this;
},
remove : function(){
$(this.el).remove();
return this;
}
});
// モデルのインスタンスを作成
var hoge = new Hoge();
// モデルを渡してビューを初期化
var hogeView = new HogeView({
model : hoge
});
}());
(function(){
// モデルの定義
var Hoge = Backbone.Model.extend({});
// コレクションの定義
var HogeList = Backbone.Collection.extend({
model : Hoge
});
// ビューの定義
var HogeView = Backbone.View.extend({
events : {
// DOMのイベントを監視
'click .submit' : 'update'
},
initialize : function(){
_.bindAll(this, 'render', 'remove');
// オブザーバーパターンを利用してモデルのイベントを購読
this.model.bind('change', this.render);
this.model.bind('destroy', this.remove);
},
update : function(){
// changeイベントが発生してrenderが実行される
...