removeEventListener() for an anonymous function
익명의 함수로된 이벤트핸들러를 removeEventListener 시키기
axiomflash
I have an event listener with an anonymous function literal, rather than a function reference. What I am trying to figure out is how to remove that event listener.
Obviously, I need a reference to the anonymous function, so the two functions are ===. But, something is going wrong… it just doesn’t work, ad this situation doesn’t generate any feedback to tell me what might be wrong.
There is some good info here (http://blogs.adobe.com/simplicity/2007/10/post.html), but not a clear explanation.
private static var _myFunc:Function;
public static function addCreditsToolTip(clip:DisplayObject):void
{
clip.addEventListener(“rollOver”,
_myFunc = function():void
{
trace(“yay!”);
});
trace(_myFunc); //”function Function() {}” < PERFECT!
clip.removeEventListener(“rollOver”, _myFunc); // < this doesn’t work
메모리 관리를 위해서 removeEventListener 는 반드시 해줘야 할텐데,
위의 코드처럼 이벤트 핸들러가 익명의 함수로 등록된 addEventListener 를 removeListener 해주기엔 딱히 방법이 없다.
그래서 30분에 걸친 구글링 끝에 찾아낸 포스팅. 나와 똑같은 고민을 하고 있구나!
너무나도 알고싶었다. 멋쟁이들의 답글을 읽어보았다.
Dazzer
You might not need to. If you trust the Garbage Collector, add this parameter
clip.addEventListener(MouseEvent.ROLL_OVER, yourFunction, false, 0 , TRUE);
the TRUE at the end indicates that the listener should be a WEAK reference, and hence does not count to the number of listeners the object has.
I’m surprised that even works though. And its not something I would recommend.
한마디로 GC 를 믿는다면 약참조만 해놓으란 소리다. 그닥 좋은 방법은 아닌듯.
Censor
Works for me in flash not sure if its what you want, hope it helps
var _myFunc:Function;
function addCreditsToolTip(clip:DisplayObject):void
{
clip.addEventListener(MouseEvent.ROLL_OVER, _myFunc = function(evt:Event):void { trace(“yay!”); clip.removeEventListener(MouseEvent.ROLL_OVER, _myFunc)})
trace(_myFunc); //”function Function() {}” < PERFECT!
}
var test:Sprite = new Sprite()
test.graphics.beginFill(0×000000)
test.graphics.drawRect(0,0,100,100)
stage.addChild(test)
addCreditsToolTip(test)
바로 이거다!
익명의 함수를 Function 으로 정의된 변수에 넣고, 익명의 함수를 마치 이벤트핸들러인양 removeEventListener 해준다. 이런 멋진 생각을! ㅎ
내일 출근하자마자 바로 써먹어봐야지.
View Full Version : removeEventListener() for an anonymous function