开发者

overloading event handler possible?

I want to extend my functio开发者_Python百科n to a better design to where I can pass a canvas object into so I don't have to write N functions.. I'm not sure as how to do this properly I've come up with a naive design with a switch but even then if I add another canvas I still need to write new code for the new canvas.

function fadeCanvasOut(event:TimerEvent):void
{ 
canvas1.alpha -= 0.1;
}

private function showForm():void
{
var myTimer:Timer = new Timer(20, 10);
myTimer.addEventListener("timer", fadeFormIn);
myTimer.start();        
}

what I need is something like:

function fadeCanvasOut(event:TimerEvent, aCanvas:Canvas):void
{ 
aCanvas.alpha -= 0.1;
}

private function showForm(aCanvas:Canvas):void
{
var myTimer:Timer = new Timer(20, 10);
myTimer.addEventListener("timer", fadeFormIn(timerEvent, canvas1);
myTimer.start();        
}

if someone could please enlighten me I would appreciate it.


If you're using ActionScript 2, then I would look into using the Delegate class for this. It will allow you to change the scope of a method call. This will change your code to this:

import mx.utils.Delegate;

function fadeCanvasOut(event:TimerEvent):void
{ 
    this.alpha -= 0.1;
}

private function showForm():void
{
    var myTimer:Timer = new Timer(20, 10);
    myTimer.addEventListener("timer", Delegate.create(canvas1, fadeCanvasOut);
    myTimer.start();        
}

If you are using ActionScript 3, Delegates are now built into the language (they removed the Delegate class, and made the element on which the event was fired the scope of the function call). This means that no longer can use you use the delegate class to change the scope to what you want. So you would now need to write it like this:

function fadeCanvasOut(event:TimerEvent, aCanvas:Canvas):void
{ 
    aCanvas.alpha -= 0.1;
}

private function showForm():void
{
    var myTimer:Timer = new Timer(20, 10);
    myTimer.addEventListener("timer", function(event:TimerEvent):void {
        fadeCanvasOut(event, canvas1);
    });
    myTimer.start();        
}


Use an inner function for this, so the scope of the canvas parameter will be preserved.

function fadeCanvasOut(event:TimerEvent, aCanvas:Canvas):void { 
  aCanvas.alpha -= 0.1;
}

private function showForm(aCanvas:Canvas):void {
  var myTimer:Timer = new Timer(20, 10);
  myTimer.addEventListener("timer", function(event:TimerEvent):void {
    fadeCanvasOut(aCanvas);
  });
  myTimer.start();        
}

On a sidenote: you might want to look at the Fade class when you want to animate an alpha property.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜