リア充爆発日記

You don't even know what ria-ju really is.

TitaniumのAlloyのControllerとViewについて調べたメモ

TitaniumのAlloy事始め。画面から別の画面に遷移するでちょっとだけ触れているけど、いざ深く画面の遷移まわりの処理を組んでいこうと思ったら、controllerとviewの境目とかわかってなくて、再度まとめてみることにした。
自分の頭の整理用メモだから、これを読んで参考になるケースは少ないと思うので、テキトウなところで去ってくだちい。

http://docs.appcelerator.com/titanium/3.0/#!/guide/Alloy_Concepts
ここに書いてあるとおり、controllerとviewは基本的に1対1の関係にある。

controllerとviewのコンパイルプロセスは上記ページには以下のとおりに書いてある。

The style, view and controller files, as well as the files in the theme's style folder and the app.tss global style file, are processed. The compiler creates a JavaScript file per view-controller and copies them to the Resources/alloy/controllers folder.

viewとかstyleとかcontrollerと組み合わせて1つのファイルにします、と。controllerには対応するviewのコンポーネントで使うfunctionを定義するので、先にviewとかstyleが処理されて、次に自分が書いたfunctionとかprogramaticに書いたviewパーツのコードなんかが続くことになる。
実際にResourcesディレクトリ配下に吐かれたコードを見ればそれはわかる。
また、このコンパイル後のコードを見ると、$ = this されているので、$はcontrollerということになる。

ところで、「controllerとviewは基本的に1対1」ということから例外があることがわかる。
例外パターンの代表格(もしくはそれ以外のパターンはないかも)が以下に掲載されていた。
http://docs.appcelerator.com/titanium/3.0/#!/guide/Views_without_Controllers

<Alloy>
    <Button id='fooButton'>I am a foo button!</Button>
</Alloy>

こんな感じの、要は画面の一部で再利用したいパーツ的なものっすね。
こういうのは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>

一方で、controller内で読み込もうと思うとAlloy.createController(view_name).getView()という形になり、具体的には以下のようなコードになる。

// Get an instance of the view
var button = Alloy.createController('foo').getView();
// Modify the view
button.bottom = 0;
button.title = 'I am not a foo button anymore.';
button.width = Ti.UI.SIZE;
button.addEventListener('click', doClick);
// Add the view
$.index.add(button);

ということは、見た目1対1じゃなくても、暗黙的にcontrollerは存在してるってことなのかな。
まあなんとなくわかった、ということにしておこう。

で、画面遷移という観点からいくと、controllerを意識すればいいのかな、というとピンとこなくて調べ始めたんだけど、やっぱりピンとこないので、公式サイトをウロウロしてたらTitanium.UI.Windowが目についた。あー、そうか。

http://docs.appcelerator.com/titanium/3.0/#!/api/Titanium.UI.Window

A window is a top-level container which can contain other views. Windows can be opened and closed. Opening a window causes the window and its child views to be added to the application's render stack, on top of any previously opened windows. Closing a window removes the window and its children from the render stack.

閉じたり開いたりできるのはWindowだけ!
controllerでは$.controller_nameもしくはWindowに付与したID名でアクセスできるってやつだね。

これでピンと来たので、この話はこれでおわり。

JavaScriptとTitaniumではじめる iPhone/Androidアプリプログラミング 【Titanium Mobile SDK 2.1 & Titanium Studio 2.1 対応】

JavaScriptとTitaniumではじめる iPhone/Androidアプリプログラミング 【Titanium Mobile SDK 2.1 & Titanium Studio 2.1 対応】