Flexで mxml でのハンドラを削除したい場合
このエントリーを見て気になったので
Flex コンポーネントの破棄 注意点 | _level0 | Kayac Front End Engineer's Blog
はてブのコメントにも書いたんだけど、ここでいう aButton がクリックされて実行される aButtonClick っていうのは、 mxml が勝手に生成してくれる Mouse.CLICK ハンドラの中で aButtonClick っていうメソッドをコールしているに過ぎないので、そもそも aButtonClick っていうメソッドが addEvent されてるわけじゃないと思うんですよね。
で、じゃあどうやってイベントを消そう?と思うと、arguments.callee を使えばいいんじゃないかと思って、以下のような感じに書いた。
元々のソースとは違って、明示的に消す、ということはできないけれど……。
無名関数で登録した場合もそうだと思うけど、メソッド名がわからないので呼ばれたタイミングで消すか、別途オブジェクトを参照するようのストアを用意しないと、キレイに消すのはできないんじゃないかな。
ま、mxml で付加される click="" とかのイベントは、対象の mxml コンポーネントが GC された時によしなにやってくれてるかもしれないけど……(そこまでは確認してない)。
ソース
wonderfl に書こうと思ったんだけど、なんか mxml を書いたらエラーになったのでこっちに貼り付けておく。
onClickHandlerっていうメソッドを、addEventListener と click="" で呼ぶようにしていて、どっちも一度実行すると、リスナーから消される。
誰得なソースを書いてしまった気がします><
<?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="init(event)"> <mx:Button x="72" y="58" label="addEventListenerButton" id="addEventListenerButton"/> <mx:Button x="261" y="58" label="clickButton" id="Button" click="onClickHandler(event, arguments.callee)"/> <mx:Script> <![CDATA[ import mx.core.UIComponent; import flash.utils.getQualifiedClassName; private function init(e:Event):void { addEventListenerButton.addEventListener(MouseEvent.CLICK, onClickHandler); } private function onClickHandler(e:Event, callee:Function = null):void { var component:UIComponent = e.currentTarget as UIComponent; textArea.text += component.id + "=>"; textArea.text += getQualifiedClassName(arguments.callee); textArea.text += " "; textArea.text += arguments.callee.toString(); textArea.text += "\n"; if(callee != null) { component.removeEventListener(MouseEvent.CLICK, callee); } else { component.removeEventListener(MouseEvent.CLICK, arguments.callee); } } ]]> </mx:Script> <mx:Label x="72" y="32" text="一度クリックされたらイベントを削除するよ" width="279"/> <mx:TextArea x="72" y="88" width="469" height="103" id="textArea"/> </mx:Application>
参考
こことかわかりやすいですかね
ActionScript3のarguments.calleeのサンプルコードがひどい - なんたらノート第三期ベータ