LoginSignup
4
4

More than 5 years have passed since last update.

Ember.js 組み込みViewクラスと、Viewクラスの実装方法

Last updated at Posted at 2012-12-12

今日は、Ember.Viewを継承した、組み込みのViewクラスを紹介します。
また、自前でカスタムViewクラスを作ってみます。

Viewクラスは、例えばinput要素をラップして、データとinput要素の値を相互にバインディングするためなどに利用します。
その他、表示の抽象化一般に使えるはず。

Viewクラスは以下のように使います。

  <h3>Your name</h3>
  {{view Ember.TextField valueBinding="name"}}

それではViewクラスを見ていきましょう。

Ember.Checkbox

名前の通り、input type="checkbox"の要素を出力します。
データ -> input要素、input要素 -> データ と、双方向のデータバインディングを行います。

{{view Ember.Checkbox checkedBinding="receiveEmail"}}

Ember.TextField

名前の通り、input type="text"の要素を出力します。
双方向のデータバインディングを行います。
type, value, size, placeholder, disabled, maxlength, tabindex属性に値をセットできます。

{{view Ember.TextField valueBinding="firstName"}}

Ember.TextArea

名前の通り、textarea要素を出力します。
双方向のデータバインディングを行います。
rows, cols, placeholder, disabled, maxlength, tabindex属性に値をセットできます。

{{view Ember.TextArea valueBinding="firstName"}}

Ember.Select

名前の通り、select要素を出力します。
双方向のデータバインディングを行います。

Ember.Select = Ember.View.extend(
{{view Ember.Select
   contentBinding="App.controller.content"
   valueBinding="App.controller.selected"
}}

contentBindingにoptionの値の配列を指定します。valueBindingはデータバインディングする変数を指定します。
対応するcontrollerの定義は以下のようになります。

App.controller = Ember.Object.create({
  selected: null,
  content: [
    "Yehuda",
    "Tom"
  ]
});

option要素をもっときめ細かく指定するときは、contentBindingにオブジェクトの配列を指定することもできます。
その時の記述は以下のようになります。

{{view Ember.Select
       contentBinding="App.controller.content"
       optionValuePath="content.id"
       optionLabelPath="content.firstName"
       selectionBinding="App.controller.selectedPerson"}}

Ember.RadioGroup

実は現在のバージョン1.0.0-pre.2には、ラジオボタンのためのViewクラスが用意されていません。ただし、ラジオボタンのサポートは以下のPull Requestが取り込まれましたので、もうすぐリリースされるはずです。備えましょう。

Ember.ContainerView

Ember.ContainerViewを使うことによって、Viewの組立をプログラムで制御することができるようになります。

var container = Ember.ContainerView.create();
container.append();
var coolView = App.CoolView.create(),
    childViews = container.get('childViews');
childViews.pushObject(coolView);

カスタムViewクラス

Ember.TextFieldをほぼコピって、input type="date" 型の要素を出力するEmber.Viewサブクラスを実装してみます。

App.DateField = Ember.View.extend(Ember.TextSupport,
    {
  classNames: ['ember-date-field'],
  tagName: "input",
  attributeBindings: ['type', 'value', 'size'],

  value: "",

  type: "date",

  size: null
});
{{view App.DateField valueBinding="start_on"}}

この程度のカスタマイズなら簡単に実装できて良い感じですね。

今回の用途なら、既存のEmber.TextFieldクラスを継承するほうがいいでしょう。(ursmさん、情報ありがとうございます!)

App.DateField = Ember.TextField.extend({
  type: "date"
});

このクラスは、上に書いたApp.DateFieldクラスと全く同じように動作します。

4
4
1

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