PDA

View Full Version : Override class method with dynamic function



xgraves
October 7th, 2009, 05:26 PM
Does anyone know if it's possible to override a custom class method with a function expression? For instance, if I want to change the destination of a button on the fly, I could theoretically type:
var new_destination:Function = function(evt:Event):void{ go_to_new_place();};
myButtonClass.mouse_clicked = new_destination; but unfortunately that generates an error because the class method "mouse_clicked" is already defined in my class (with the eventListener tied to it). I tried using the "override" keyword in the Function Expression but that didn't work either. Grrr.

senocular
October 7th, 2009, 05:45 PM
Not exactly, no. But you could create a function variable and re-assign the value of that.


package {

import flash.display.Sprite;
import flash.events.MouseEvent;

public class MySprite extends Sprite {

public var onPress:Function; // assign to change CLICK event

public function MySprite(){
super();
addEventListener(MouseEvent.CLICK, clickHandler);
onPress = defaultOnPress;
}

private function clickHandler(event:MouseEvent):void {
if (onPress != null){
onPress(event);
}
}

private function defaultOnPress(event:MouseEvent):void {
trace("onPress");
}
}
}

efos
October 7th, 2009, 05:51 PM
Taking a shot in the dark here, maybe try something like this?



private var fnMouse:Function
public function set mouse_clicked(f:Function):void{
removeEventListener(MouseEvent.MOUSE_CLICK,fnMouse )
fnMouse = f
addEventListener(MouseEvent.MOUSE_CLICK,fnMouse)
}I would suggest simply using: addEventListener(MouseEvent.MOUSE_CLICK,f)

But I don't know how you would remove the previous assignment.

If anyone knows how to strip all EventListeners off an object (without knowing exactly what they are) I would love to know.

Edit: Oooh, I like senocular's better.

xgraves
October 7th, 2009, 05:53 PM
Ah, genius! Thanks senocular. You are truly a kung foo master.