2

Basically I have this function:

private function clickURL(url:String):Function{
    trace("Function has been instantiated");
    return function(event:MouseEvent):void{
        trace("Function has been run");
        ExternalNavigation.newBrowserWindow(url);
    }
}

The purpose of this function is to take an url, put the url in another function and pass that function back so I can just type:

urlButton.addEventListener(MouseEvent.CLICK, clickURL("http://test.com"));

The function clickURL will return the function with the event parameter back to the addEventListener function. In that way I specify what url which will be opened when you press the button.

Here's the output of what happens when you use it:

//Function has been instantiated

The internatl function never gets run when you click the button. So I thought I'd try it out with a fake event to be sure I didn't miss anything.

var clickTest:Function = clickURL("http://stackoverflow.com");
clickTest(new MouseEvent(MouseEvent.CLICK));

Here's the output:

//Function has been instantiated
//Function has been run

As you can see, both functions are run. Have anyone got an idea to why this is working and not with the addEventListener?

Regards Z

4

2 回答 2

1

这应该没有问题......

如果你这样做urlButton.addEventListener(MouseEvent.CLICK, trace);并单击按钮,你会得到任何痕迹吗?

编辑:

我真的无法重现它......这里有一些可以完美运行的代码:

package {
    import flash.display.*;
    import flash.events.*;
    public class Main extends Sprite {
        private var urlButton:Sprite;
        public function Main():void {
            this.addChild(this.urlButton = new Sprite());
            this.urlButton.graphics.beginFill(0xFF00FF);
            this.urlButton.graphics.drawRect(0, 0, 200, 50);
            urlButton.buttonMode = true;
            urlButton.addEventListener(MouseEvent.CLICK, clickURL("http://test.com"));
        }
        private function clickURL(url:String):Function{
            trace("Function has been instantiated");
            return function(event:MouseEvent):void{
                trace("Function has been run");
            }
        }       
    }
}

你可以发布/上传一个最小的设置,它不起作用吗?

问候

back2dos

于 2009-06-26T19:57:06.447 回答
-1

我马上看到的一个问题是变量 url 仅在函数初始化为侦听器时存在,但在通过鼠标事件触发时不存在。所以它实际上会在执行时收到一个空值。(或抛出错误)

正如您所演示的,当触发事件时,侦听器已按预期设置和执行,因此如果您的按钮未正确触发事件,那么按钮可能存在问题?

于 2009-06-26T15:51:19.440 回答