LoginSignup
1
1

More than 5 years have passed since last update.

Ember.js テンプレートの中で、thisが使える

Last updated at Posted at 2012-12-26

2013/1/14 最近の変更で、{{view XxxView content="this"}} ではなく {{view XxxView contentBinding="this"}} と書かないと通らなくなってたのでその点修正しました。

これまでのサンプルで、テンプレートも書いてきてたのですが、eachを使った時に各オブジェクトを取得する方法がわかってませんでした。

どうやるのか調べてみたところ、テンプレートの中で this でコンテキストオブジェクトを参照できることがわかりました。これを使えば、各アイテムに対してactionを仕掛けることもできます。

App = Ember.Application.create()

# Controllers
App.entries = Ember.ArrayController.create
  content: [
    Ember.Object.create(id: 1, body: 'hoge'),
    Ember.Object.create(id: 2, body: 'moge'),
    Ember.Object.create(id: 3, body: 'koge'),
  ]

# Views
App.ApplicationView = Ember.View.extend()

App.EntriesView = Ember.View.extend
  templateName: 'entries',
  entriesBinding: 'App.entries.content'

App.EntryView = Ember.View.extend
  templateName: 'entry',
  alert: (->
    alert(this.get('content').get('body'))
  ),
  content: null # 初期化時にセット

ArrayControllerのインスタンスと、それを表示するためのviewを定義しています。EntryViewはApp.entriesの各アイテムごとに生成され、アイテムはcontentメンバにセットされる想定です。

  <script type="text/x-handlebars">
    {{view App.EntriesView}}
  </script>

  <script type="text/x-handlebars" data-template-name="entries">
    {{#each view.entries}}
      {{view App.EntryView contentBinding="this"}}
    {{/each}}
  </script>

  <script type="text/x-handlebars" data-template-name="entry">
    <div>
      {{id}}
      {{body}}
      <button {{action "alert"}}>alert</button>
    </div>
  </script>

App.EntryViewのインスタンスを挿入している箇所で、viewのcontentメンバにthisをセットしています。これにより、viewに各アイテムを割り当てることができます。あとはApp.EntryViewの中で、セットされたアイテムを参照できます。alertボタンを押すと、アイテムの内容を表示します。

以下のページでプログラムの動作を確認できます。

デモ
http://kmdsbng.github.com/emberjs_each_action/

ソース
https://github.com/kmdsbng/emberjs_each_action/blob/master/index.html
https://github.com/kmdsbng/emberjs_each_action/blob/master/js/app.coffee

1
1
0

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
1
1