removeEventListener for anon function in AS3
I need to disable an onClick action until an animation has stopped. Animations can be started by 4 different buttons - all need to be deactivated.
I use a listener to pass params to the function that will initiate the animation which is why I use an anonymous function in the add listener:
up.addEventListener(MouseEvent.CLICK,
function(event:MouseEvent):void
{
开发者_JS百科 revealSpinner(event,51.42,1,spinner);
event.currentTarget.removeEventListener(event.type, arguments.callee);
},
false, 0, true);
I also have a self calling remove listener, but really I need to remove the listener from the other 3 buttons.
I have also tried naming the anonymous function but that didn't work:
up.addEventListener(MouseEvent.CLICK,
myFunc = function(event:MouseEvent):void
{
revealSpinner(event,51.42,1,spinner);
},
false, 0, true);
// somewhere else in my app
up.removeEventListener(MouseEvent.CLICK, myFunc );
Edit: each of the 4 buttons has to pass different parameters to the revealSpinner() method revealSpinner(event,51.42,1,spinner); revealSpinner(event,51.42,-1,spinner); revealSpinner(event,120,1,anotherMC); revealSpinner(event,120,-1,anotherMC);
You can use the event.currentTarget parameter as you have already shown but in a callback function. Just use a switch statement to set the parameters depending on how the function was called:
function setupButtons()
{
...
this.up.addEventListener(MouseEvent.CLICK, cbButtonClick, false, 0, true );
this.down.addEventListener(MouseEvent.CLICK, cbButtonClick, false, 0, true );
}
function cbButtonClick( event:MouseEvent ):void
{
switch( event.currentTarget )
{
case this.up:
revealSpinner(event,51.42,1,spinner);
break;
case this.down:
revealSpinner(event,999999,1,spinner);
break;
}
event.currentTarget.removeEventListener(event.type, cbButtonClick);
}
Don't use anonymous functions. If you define a handler for each button you can still pass your custom parameters, but you'll have a properly defined listener that can be removed at any point:
up.addEventListener(MouseEvent.CLICK, upButtonHandler, false, 0, true);
function upButtonHandler(event:MouseEvent):void
{
revealSpinner(event,51.42,1,spinner);
up.removeEventListener(MouseEvent.CLICK, upButtonHandler);
}
down.addEventListener(MouseEvent.CLICK, downButtonHandler, false, 0, true);
function downButtonHandler(event:MouseEvent):void
{
revealSpinner(event,999.999,999,spinner);
down.removeEventListener(MouseEvent.CLICK, downButtonHandler);
}
精彩评论