tixture55’s diary

主にプログラミング関係の日記です。

backbone.jsの基本的な使い方

backbone.jsを学習したので、学んだところをまとめてみた。

 

Viewの作成

  Viewの設定の書き方は下記の通り。

2
3
4
5
6
7
8
9
var TaskView = Backbone.View.extend({
   tagName: 'li',
className: 'liClass',
id: 'liId',
template: _.template("<%- title %>")
 
render: function() {
var template = this.template(this.model.toJSON() );
this.$el.html(template);
return this;
}
  
});
 
var taskView = new TaskView({ model: task });
 

このように、modelの値と組み合わせて使うことができる。やや記述方法に癖があり、ちょっと慣れるまでに時間がかかるかもしれないが、viewとmodelのbind処理はそんなに複雑ではなく一安心。

 

またevent処理をviewに書くことで、イベントドリブン処理も実装できる。

2
3
4
5
6
7
8
9
events : {
   'click #editBtn' : 'edit',
    'click #deleteBtn' : 'delete',
    'change #name' : 'chageName'
},

 例えば、editのメソッドには下記のように書ける。

 

edit : function() {
        var name = this.$el.find('#name').val();
        var birthday = this.$el.find('#birthday').val();
        var position = this.$el.find('#position').val();
        var number = this.$el.find('#number').val();
        var hobby = this.$el.find('#hobby').val();
        var zeal = this.$el.find('#zeal').val();・・・以下略