Copy link to clipboard
Copied
I'm having trouble removing event listeners from movie clips. As a test I put two MCs on stage: keyB and remover.
I want to pass a parameter to the keyB event listener function. This works fine. But when I try to remove the listener it doesn't work.
keyB.addEventListener(MouseEvent.CLICK, function (evt:MouseEvent):void {keyHandler(evt,"b")});
remover.addEventListener(MouseEvent.CLICK, removeHandler);
function keyHandler(evt:MouseEvent, char:String):void {
trace(char);
}
function removeHandler(evt:MouseEvent):void {
keyB.removeEventListener(MouseEvent.CLICK, function (evt:MouseEvent):void {keyHandler(evt,"b")});
keyB.alpha=.5
}
Found the solution here:
//you can pass parameter to the function this way:
stage.addEventListener(MouseEvent.CLICK, onClick(true, 123, 4.56, "string"));
function onClick(b:Boolean, i:int, n:Number, s:String):Function {
return function(e:MouseEvent):void {
trace("Received " + b + ", " + i + ", " + n + " and " + s + ".");
};
}
//But to be able to remove the listen
...Copy link to clipboard
Copied
Found the solution here:
//you can pass parameter to the function this way:
stage.addEventListener(MouseEvent.CLICK, onClick(true, 123, 4.56, "string"));
function onClick(b:Boolean, i:int, n:Number, s:String):Function {
return function(e:MouseEvent):void {
trace("Received " + b + ", " + i + ", " + n + " and " + s + ".");
};
}
//But to be able to remove the listener you store the function in a variable that is a function = the function call in the listener.
//then call that function in the listener.
var functionOnClick:Function = onClick(true, 123, 4.56, "string");
stage.addEventListener(MouseEvent.CLICK, functionOnClick);
function onClick(b:Boolean, i:int, n:Number, s:String):Function {
return function(e:MouseEvent):void {
trace("Received " + b + ", " + i + ", " + n + " and " + s + ".");
};
}
trace("Before: " + stage.hasEventListener(MouseEvent.CLICK));
stage.removeEventListener(MouseEvent.CLICK, functionOnClick);
trace("After: " + stage.hasEventListener(MouseEvent.CLICK));
Find more inspiration, events, and resources on the new Adobe Community
Explore Now