2014年9月29日月曜日

Titanium Tips: Alloy での部品化

Titanium の開発の中で部品化のために出てくる
  1. View 内から require で別の View を読み込む 
  2. Controller 内から createController で 別 View/Controler を動的生成
  3. controller 内で require による CommonJS モジュールの読み込み
辺りについて簡単なメモ。
(半分自分向けのポイントのみのまとめです。
 実例を交えた詳しい説明はすでに色々なサイトでされているので・・・
 後、widget という手もありますが、手を出してないので省略)

1. View 内から require で別の View を読み込む

公式ドキュメントとしては Alloy XML Markup内の Require Element

この方法で View 内で別の View を読み込むことが出来ます。
<Require type="view" src="about" id="aboutTab"/> ← about.xml に定義した View
View に対応した Controller(~.js)はあっても無くてもOK。
("Views can be created without controllers with an optional style sheet"@ Views without Controllers

また、クラスのインスタンス化的に同じ View を複数回 require しても可。

<Alloy>
 <Window layout="vertical">
    <Require id="button1" src="foo" type="view"/>
    <Require id="button2" src="foo" type="view"/>
    <Require id="button3" src="foo" type="view"/>
  </Window>
</Alloy>

単純にソースの見やすさ・管理のしやすさ、ということだけではなく、一つの View 定義の使い回しが可能です。

では、その分かれた View に対して、require する側からアクセスするには、 xml で指定した id ベースになります。
汎用例:var object = $.requireId.getView('objectId');
例えば、require で指定した id が aboutTab、読み込む src 内にある view の id が aboutView の場合、それを取得するには、
var aboutView = $.aboutTab.getView('aboutView'); 
となります。
ちなみに、 undocumented なやり方ですが id をつなげるだけでもアクセスできるようです。
例えば、上の例ならば次のような形になります。
$.aboutTab.aboutView

2. Controller 内から createController で 別 View/Controler を動的生成

公式ドキュメントとしては Alloy Controllers 辺りでしょうか。

Controller 内から独立した View, Controller を動的生成する場合には Alloy.createController() を使い、getView() で View を取得します。
var about = Alloy.createController('about', args).getView();
about.open();
これで about.xml, about.tss, about.js で定義された1セットをインスタンス化できるわけです。
またこの際に、引数を渡すことができるので(上記の args)、そこで様々な情報を引き渡すこともできます。

3. controller 内で require による CommonJS モジュールの読み込み


公式ドキュメントとしては CommonJS Modules in Titanium
複数の Controller で使うコードを、独立・共通化して記述することが可能です。

app/lib/ 配下に .js ファイルを配置して、require で読み込めば利用できます。

モジュール側は CommonJS に則った書き方になりますが、
  • exports - a free variable within a module, to which multiple properties may be added to create a public interface
  • module.exports - an object within a module, which may be REPLACED by an object representing the public interface to the module
とモジュール側からの公開方法は2通りの方法があります。

exports は require で読み込んだ側のオブジェクトでプロパティを参照する方式。

module.exports の場合には、require で読み込んだオブジェクトがそのままモジュール側で指定したものに置き変わる形。
module.exports はクラスを定義してそれを丸ごと公開するようなものに向いています。
(公式ドキュメントの Person の例などが分かりやすい)

0 件のコメント:

コメントを投稿