I have learned this method of passing values with addEventLister. Here is the code:
for (var i:uint = 0; i < asteroids.length; i++)
{
asteroids[i].x = Math.random() * 450;
asteroids[i].y = Math.random() * 450;
asteroids[i].addEventListener(MouseEvent.MOUSE_UP, function(e:MouseEvent){
changeValue(e, otherArguments);
});
}
public function changeValue(event:MouseEvent, otherArguments:Object):void
{
playSound(anote);
trace(event.currentTarget);
}
but there is no explanation about how to remove the event listener from
asteroids[i].addEventListener(MouseEvent.MOUSE_UP, function(e:MouseEvent){
changeValue(e, otherArguments);
});
That is because you cannot unhook an anonymous function if you don’t have a reference to it. If you’d like, you can always keep a reference around:
Of course, if these things are happening in separate member functions, then you need to define a member variable (
var asteroidsMouseUpHandler:Function). At that point, you might just want to create it as a named function instead. You’d also only want to do this once (not in a loop) to avoid clobbering your reference. Really, I am showing this code for illustrative purposes only.Thinking about this further, you might be doing this because the
otherArgumentsis specific to the particularasteroids[i]instance so that you are actually creating a new anonymous function every time you hook it. In that case, if that is what you really want to do, you can keep track of your anonymous functions in a dictionary:Then, you can keep track of the functions there:
And then when you want to unhook, you can look it up:
Of course, I am ignoring existential checks for simplicity. You’d have to add that as well.