🍃このブログは移転しました。
3秒後、自動的に移動します・・・。

Backbone.js Todosを読み解く

というわけで色々Backbone.jsについて見てはいるものの、いざ自分で作ってみると上手くいかない・・。
ようはどの単位でViewとModelを紐付ければ良いかわからないんですよねー。

というわけで、Todoリストのサンプルからそのヒントを得ようという試み。

参考:Backbone.js Todos

Backbone.js Todosについて

見ての通りBackbone.jsで作られたサンプルアプリ。
Todoリストのデータの保管にはLocalStorageを使ってて、別のライブラリを読み込んでます。

ソース全部

せっかくなので、ソースについてるコメントを和訳しときます。

// An example Backbone application contributed by
// [Jérôme Gravel-Niquet](http://jgn.me/). This demo uses a simple
// [LocalStorage adapter](backbone-localstorage.html)
// to persist Backbone models within your browser.

// [Jérôme Gravel-Niquet](http://jgn.me/)氏によるBackboneアプリのサンプル。
// データ保持のために、[LocalStorage adapter](backbone-localstorage.html)を使用。

// Load the application once the DOM is ready, using `jQuery.ready`:
// jQuery.readyでアプリをDOMロード時に起動
$(function(){

  // Todo Model
  // ----------

  // Our basic **Todo** model has `title`, `order`, and `done` attributes.
  // Todoのタスク自身のモデル。`title`、`order`、`done`から構成される。
  var Todo = Backbone.Model.extend({

    // Default attributes for the todo item.
    // 初期値の設定
    defaults: function() {
      return {
        title: "empty todo...",
        order: Todos.nextOrder(),
        done: false
      };
    },

    // Toggle the `done` state of this todo item.
    // ステータスのトグルのための関数
    toggle: function() {
      this.save({done: !this.get("done")});
    }

  });

  // Todo Collection
  // ---------------

  // The collection of todos is backed by *localStorage* instead of a remote
  // server.
  // Todoタスク達を集めたCollection。(サーバーの代わりにlocalStorageを使用)
  var TodoList = Backbone.Collection.extend({

    // Reference to this collection's model.
    // Collectionの生成時にはどのModelを並べるか指定します。
    model: Todo,

    // Save all of the todo items under the `"todos-backbone"` namespace.
    // todos-backboneという名前空間で、localStorageを使用。
    localStorage: new Backbone.LocalStorage("todos-backbone"),

    // Filter down the list of all todo items that are finished.
    // doneステータスになってるものを返す関数
    done: function() {
      return this.where({done: true});
    },

    // Filter down the list to only todo items that are still not finished.
    // 逆に、doneステータスになってないものを返す関数
    remaining: function() {
      return this.without.apply(this, this.done());
    },

    // We keep the Todos in sequential order, despite being saved by unordered
    // GUID in the database. This generates the next order number for new items.
    // DBにおけるGUIDのように連番で管理したいので、その連番を採取する関数
    nextOrder: function() {
      if (!this.length) return 1;
      return this.last().get('order') + 1;
    },

    // Todos are sorted by their original insertion order.
    // comparatorを設定すると、それ順でCollectionが並ぶ
    comparator: 'order'

  });

  // Create our global collection of **Todos**.
  // Collectionのインスタンス化
  var Todos = new TodoList;

  // Todo Item View
  // --------------

  // The DOM element for a todo item...
  // 各Todoタスク用のView
  var TodoView = Backbone.View.extend({

    //... is a list tag.
    // 実態はliタグ
    tagName:  "li",

    // Cache the template function for a single item.
    // Underscore.jsのテンプレ機能を使うので、ここにキャッシュしておく
    template: _.template($('#item-template').html()),

    // The DOM events specific to an item.
    // このViewで管理したいDOMイベントと、関数の結びつけ
    events: {
      "click .toggle"   : "toggleDone",
      "dblclick .view"  : "edit",
      "click a.destroy" : "clear",
      "keypress .edit"  : "updateOnEnter",
      "blur .edit"      : "close"
    },

    // The TodoView listens for changes to its model, re-rendering. Since there's
    // a one-to-one correspondence between a **Todo** and a **TodoView** in this
    // app, we set a direct reference on the model for convenience.
    // Modelの更新を検知してViewを更新するために、ModelをlistenToしておく
    // よって、ModelのTodoとViewのTodoViewは1:1で紐づくことになる
    initialize: function() {
      this.listenTo(this.model, 'change', this.render);
      this.listenTo(this.model, 'destroy', this.remove);
    },

    // Re-render the titles of the todo item.
    // Modelの内容をHTMLに落としこむ関数
    render: function() {
      this.$el.html(this.template(this.model.toJSON()));
      this.$el.toggleClass('done', this.model.get('done'));
      this.input = this.$('.edit');
      return this;
    },

    // Toggle the `"done"` state of the model.
    // Modelのdoneステータスをトグルする関数
    toggleDone: function() {
      this.model.toggle();
    },

    // Switch this view into `"editing"` mode, displaying the input field.
    // 編集モードに移行する関数
    edit: function() {
      this.$el.addClass("editing");
      this.input.focus();
    },

    // Close the `"editing"` mode, saving changes to the todo.
    // 編集モードを終了する関数
    close: function() {
      var value = this.input.val();
      if (!value) {
        this.clear();
      } else {
        this.model.save({title: value});
        this.$el.removeClass("editing");
      }
    },

    // If you hit `enter`, we're through editing the item.
    // エンターキーで上記のclose()を実行する関数
    updateOnEnter: function(e) {
      if (e.keyCode == 13) this.close();
    },

    // Remove the item, destroy the model.
    // Modelの削除時に使う関数
    clear: function() {
      this.model.destroy();
    }

  });

  // The Application
  // ---------------

  // Our overall **AppView** is the top-level piece of UI.
  // トップレベルのViewとして、AppViewを定義
  var AppView = Backbone.View.extend({

    // Instead of generating a new element, bind to the existing skeleton of
    // the App already present in the HTML.
    // 既に定義済のHTML要素にAppViewは適応することにする
    el: $("#todoapp"),

    // Our template for the line of statistics at the bottom of the app.
    // 下の方で残り○タスクって表示するところのためのテンプレ
    statsTemplate: _.template($('#stats-template').html()),

    // Delegated events for creating new items, and clearing completed ones.
    // 新タスクの作成のイベントなど、AppViewで監視するイベントなどなど
    events: {
      "keypress #new-todo":  "createOnEnter",
      "click #clear-completed": "clearCompleted",
      "click #toggle-all": "toggleAllComplete"
    },

    // At initialization we bind to the relevant events on the `Todos`
    // collection, when items are added or changed. Kick things off by
    // loading any preexisting todos that might be saved in *localStorage*.
    // CollectionのイベントをlistenToすることで、Viewをrenderする算段
    // 最後のfetchが実行されると、Collectionのresetイベントが発火してaddAll関数実行!
    initialize: function() {

      this.input = this.$("#new-todo");
      this.allCheckbox = this.$("#toggle-all")[0];

      this.listenTo(Todos, 'add', this.addOne);
      this.listenTo(Todos, 'reset', this.addAll);
      this.listenTo(Todos, 'all', this.render);

      this.footer = this.$('footer');
      this.main = $('#main');

      Todos.fetch();
    },

    // Re-rendering the App just means refreshing the statistics -- the rest
    // of the app doesn't change.
    // ここでは残りタスク数の整理だけを行う
    render: function() {
      var done = Todos.done().length;
      var remaining = Todos.remaining().length;

      if (Todos.length) {
        this.main.show();
        this.footer.show();
        this.footer.html(this.statsTemplate({done: done, remaining: remaining}));
      } else {
        this.main.hide();
        this.footer.hide();
      }

      this.allCheckbox.checked = !remaining;
    },

    // Add a single todo item to the list by creating a view for it, and
    // appending its element to the `<ul>`.
    // 新しいタスクViewを作って、親ulにliとして突っ込む(ここでやっとModelがDOMに落ちる
    addOne: function(todo) {
      var view = new TodoView({model: todo});
      this.$("#todo-list").append(view.render().el);
    },

    // Add all items in the **Todos** collection at once.
    // Collectionの中のModelの分だけaddOne関数
    addAll: function() {
      Todos.each(this.addOne, this);
    },

    // If you hit return in the main input field, create new **Todo** model,
    // persisting it to *localStorage*.
    // AppViewでエンターキーすると、新しいModel、新しいタスクViewができる
    createOnEnter: function(e) {
      if (e.keyCode != 13) return;
      if (!this.input.val()) return;

      Todos.create({title: this.input.val()});
      this.input.val('');
    },

    // Clear all done todo items, destroying their models.
    // doneステータスになってるModelを削除する
    clearCompleted: function() {
      _.invoke(Todos.done(), 'destroy');
      return false;
    },

    toggleAllComplete: function () {
      var done = this.allCheckbox.checked;
      Todos.each(function (todo) { todo.save({'done': done}); });
    }

  });

  // Finally, we kick things off by creating the **App**.
  // 最後にAppViewをインスタンス化
  var App = new AppView;

});

気付いたこと

アプリView

やっぱりそうか、って感じですが・・。
Backbone.js自体がシングルページのアプリ向き・・みたいな話をよく聞きますね。
そのアプリ全体を司るViewがいて、各子Viewが構成要素になってるんですね。

fetch()でresetイベント

このアプリの仕組みでのなるほどポイント。
AppViewのinitializeでfetchすることで、resetイベント→addAllでデータ復帰・・と。

シンプル!

取っ付くまではなんだコレでしたが、意味がわかるようになってからは本当にシンプルに書けるんやなーと感動してます。
そしてコレは良いサンプルだわ・・。

Modelの最小単位が表すものがViewの最小単位

何を言ってるんだ的な感じですが、個人的に一番のハラオチポイントがコレ。
最初に自分で作ったときに、TodoListViewみたいな感じでCollectionと結びつけてViewを組んでしまったんですよね。
そしたらそれぞれのタスクをDoneしたことを、どうやって当該Modelに知らせるかがわからなくって。

そもそもCollectionをまとめてrenderするんじゃなくて、Modelをeachでrenderしないといけないんやなーと。

ここの見極めが一番むずかしいけど、コレさえできればなんとかなりそうね。