Backbone.jsのViewを復習 その1

https://app.codegrid.net/entry/backbone-view

by FiNGAHOLiC

HTML

<script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.4.4/underscore-min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/backbone.js/0.9.10/backbone-min.js"></script>
<script src="https://getfirebug.com/firebug-lite-debug.js"></script>
<div class="lists1"></div>
<div class="lists2"></div>
<script type="text/template" class="js-tmpl-item">
    <input type="checkbox"><span><%= text %></span>
</script>

JavaScript

(function(){
    // クラス内でelを設定
    var TodoList = Backbone.View.extend({
        el: '.lists1'
    });
    var todolist = new TodoList();
    // HTMLエレメント
    console.log(todolist.el);
    // jQueryオブジェクトも作成してくれている
    console.log(todolist.$el);
}());

(function(){
    // インスタンス作成時にelを指定
    var TodoList = Backbone.View.extend({});
    var todolist = new TodoList({ el: '.lists1' });
    // HTMLエレメント
    console.log(todolist.el);
    // jQueryオブジェクトも作成してくれている
    console.log(todolist.$el);
}());

(function(){
    // 新規に要素を作成する場合
    var TodoListItem = Backbone.View.extend({
        tagName: 'div',
        className: 'list'
    });
    var todolistitem = new TodoListItem();
    // HTMLエレメント
    console.log(todolistitem.el);
    // jQueryオブジェクトも作成してくれている
    console.log(todolistitem.$el);
}());

(function(){
    
    var TodoList = Backbone.View.extend({
        add: function(text){
            var item = new TodoListItem({ text: text });
            this.$el.append(item.el);
        }
    });
    
    var TodoListItem = Backbone.View.extend({
        className: 'list',
        events: {
            'change input[type="checkbox"]': 'onChangeCheckbox'
        },
        initialize: function(){
            var html = '<input type="checkbox"> ' + this.options.text;
            this.$el.html(html);
        },
        onChangeCheckbox: function(){
            console.log('clicked');
        }
    });
    
    // .lists1以下を管理するビューを作成
    var todolist = new TodoList({ el: '.lists1' });
    
    // 要素を追加
    todolist.add('hogehogehoge');
    todolist.add('fugafugafuga');
    
}());

(function(){
    var Todo = Backbone.Model.extend({});
    var Todos = Backbone.Collection.extend({
        model: Todo
    });
    var TodoList = Backbone.View.extend({
        initialize: function(){
            this.collection.on('add', this.add, this);
        },
        add: function(todo){
            console.log('add model');
        }
    });
    
    var todos = new Todos([
        {...