LoginSignup
3

More than 5 years have passed since last update.

Backbone.jsでHello World (Backbone.Viewのサンプル)

Last updated at Posted at 2016-03-21

前提

  • 可能な限りES2015を使います

準備

Backbone.jsはjQueryとunderscoreに依存しています。
準備を簡単にするために、各ライブラリをCDNから取得します。

<head>
  <script src="https://code.jquery.com/jquery-2.2.2.js" integrity="sha256-4/zUCqiq0kqxhZIyp4G0Gk+AOtCJsY1TA00k5ClsZYE=" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.3.2/backbone.js"></script>
</head>

Hello Wolrd

GIFアニメ

ボタンを押すと、alertを表示するサンプルです。

out.gif

ソースコード

<head>
  <script src="https://code.jquery.com/jquery-2.2.2.js" integrity="sha256-4/zUCqiq0kqxhZIyp4G0Gk+AOtCJsY1TA00k5ClsZYE=" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.3.2/backbone.js"></script>
</head>

<body>
  <div class="container">
    <button>say hello</button>
  </div>

  <script>
    const AppView = Backbone.View.extend({
      el: '.container',
      events: {
        'click button': () => alert('hello')
      }
    })
    new AppView
  </script>
</body>

Viewクラスの動作解説

ユーザーイベントの処理を書く場合はViewを使います。
ViewはBackbone.View.extendの形式でカスタマイズしたコンストラクタを作ります。

extendメソッド

extendメソッドは、Backbone.jsの提供する全モジュールで共通のAPIです。

  // Set up inheritance for the model, collection, router, view and history.
  Model.extend = Collection.extend = Router.extend = View.extend = History.extend = extend;

第一引数に指定したオブジェクトでインスタンスプロパティを設定します。

    // Set the prototype chain to inherit from `parent`, without calling
    // `parent`'s constructor function and add the prototype properties.
    child.prototype = _.create(parent.prototype, protoProps);
    child.prototype.constructor = child;

elプロパティ

既存のDOMにイベントハンドラーを設定したい時は、対象のDOMをelプロパティで設定します。

elプロパティを設定した場合

初期化時に$(el)で取得したDOM要素を、elプロパティに設定しなおします。

      this.$el = el instanceof Backbone.$ ? el : Backbone.$(el);
      this.el = this.$el[0];

Backbone.$はjQueryへの参照です。

  Backbone.$ = $;

elプロパティを設定しない場合

初期化時に作成したDOM要素を、elプロパティに設定します。

        this.setElement(this._createElement(_.result(this, 'tagName')));

eventsプロパティ

イベントハンドラーはオブジェクトを使ったマップを指定できます。

      for (var key in events) {
        var method = events[key];
        if (!_.isFunction(method)) method = this[method];
        if (!method) continue;
        var match = key.match(delegateEventSplitter);
        this.delegate(match[1], match[2], _.bind(method, this));
      }

バリューに関数を指定した場合は、その関数を使います。
文字列を指定した場合は、自インスタンスのメソッドを呼び出します。

        if (!_.isFunction(method)) method = this[method];

イベントハンドラーをバインド

作成したコンストラクタを呼び出すと、イベントハンドラーをバインドします。

コンストラクタから_ensureElementを呼び

    this._ensureElement();

setElementを呼び

        this.setElement(_.result(this, 'el'));

delegateEventsを呼びます。

      this.delegateEvents();

alertをhtml上のメッセージ表示に変更

click buttonのイベントハンドラーを修正します。

<head>
  <script src="https://code.jquery.com/jquery-2.2.2.js" integrity="sha256-4/zUCqiq0kqxhZIyp4G0Gk+AOtCJsY1TA00k5ClsZYE=" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.3.2/backbone.js"></script>
</head>

<body>
  <div class="container">
    <button>say hello</button>
    <span class="message"></span>
  </div>

  <script>
    const AppView = Backbone.View.extend({
      el: '.container',
      events: {
        'click button': function() {
          this.$el.find('.message').text('hello')
        }
      }
    })
    new AppView
  </script>
</body>

$elプロパティにはViewインスタンスがターゲットとするDOMの、jQueryオブジェクトが入っています。
thisでViewインスタンスを参照して、プロパティを取得します。
アロー関数ではなく、無名関数を使います。

jQueryを使わない場合

elプロパティにViewインスタンスがターゲットとするDOMが入っています。

this.$el.find('.message').text('hello')

this.el.querySelector('.message').innerText = 'hello'

と書いても良いでしょう。

関連記事

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3