ActionScriptも自分でコンポーネント作ったりしてるとJavaのSwingやってるような気がしてくる。
自作コンポーネントの中の部品を初期化する。例えば下のような感じ。
SampleTab.mxml:
<?xml version="1.0" encoding="utf-8"?>
<mx:TabNavigator xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Canvas label="タブ1" width="100%" height="100%" id="myCanvas">
<view:MyComponent x="0" y="0" width="100%" height="100%"
id="myComponent"
>
</view:MyComponent>
</mx:Canvas>
<mx:Canvas label="タブ2" width="100%" height="100%">
</mx:Canvas>
</mx:TabNavigator>
ここではトップのSampleTab(TabNavigator)が自作のコンポーネントであり、タブを二つ持つようなものを考えている。さらにタブ1はまた別の自作コンポーネント(MyComponent)を内包しているとする(まあ、別に自作コンポーネントじゃなくてもいいけど)。で、このMyComponentは特殊な感じになっているのでSampleTabを初期化した時点で独自のロジックでこれも初期化したいと。TabNavigatorを子要素に持つ奴が、MyComponentの初期化処理も行いたい、つまり孫コンポーネントを初期化したいというわけです。
で、まずアプリケーションの初期化メソッドをinit()とすると
public function init():void {
var sampleTab:SampleTab = new SampleTab();
sampleTab.addEventListener(FlexEvent.CREATION_COMPLETE, myComponentInit);
・・・
}
public function myComponentInit(event:FlexEvent):void {
var sampleTab:SampleTab = SampleTab(event.target);
sampleTab.myComponent.~~~
・・・
}
って感じでやろうとしたらだめだった。sampleTabが作成された段階ではまだmyComponentまではできてない。そしてsampleTab.myComponentはnullになる。
というわけで、以下のようにした。
<?xml version="1.0" encoding="utf-8"?>
<mx:TabNavigator xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script>
<![CDATA[
public var myComponentInit:Function;
]]>
</mx:Script>
<mx:Canvas label="タブ1" width="100%" height="100%" id="myCanvas">
<view:MyComponent x="0" y="0" width="100%" height="100%"
id="myComponent"
creationComplete="myComponentInit(event)"
>
</view:MyComponent>
</mx:Canvas>
<mx:Canvas label="タブ2" width="100%" height="100%">
</mx:Canvas>
</mx:TabNavigator>
public function init():void { var sampleTab:SampleTab = new SampleTab(); sampleTab.myComponentInit = myComponentInit; ・・・ } public function myComponentInit(event:FlexEvent):void { var myComponent:MyComponent = MyComponent(event.target); myComponent.~~ ・・・ }
関数ポインタ的に。
動いているが、自作のコンポーネントの作り方を根本的に間違っている気がしないでもない。だがしかし!動けばそれが答えさ!
以上