actionscript-3 - 如何将参数传递给 flex/actionscript 中的事件监听器函数?

标签 actionscript-3 flash apache-flex events arguments

因为在使用 sql lite 时,如果您同时尝试执行一个函数会引发错误,我只是尝试创建一个函数来检查它是否正在执行,如果在 10 毫秒内再次尝试,这个确切的函数可以正常工作如果我不必向函数传递任何参数,但我很困惑如何将变量传递回它将执行的函数。

我想要做:

timer.addEventListener(TimerEvent.TIMER, saveChat(username, chatBoxText));

但它只会让我做:
timer.addEventListener(TimerEvent.TIMER, saveChat);

它给了我这个编译错误:

1067: Implicit coercion of a value of type void to an unrelated type Function



我怎样才能让它通过这个限制?

这是我所拥有的:
public function saveChat(username:String, chatBoxText:String, e:TimerEvent=null):void
{
    var timer:Timer = new Timer(10, 1);
    timer.addEventListener(TimerEvent.TIMER, saveChat);

    if(!saveChatSql.executing)
    {
        saveChatSql.text = "UPDATE active_chats SET convo = '"+chatBoxText+"' WHERE username = '"+username+"';";
        saveChatSql.execute();
    }
    else timer.start();
}

最佳答案

监听器调用的函数只能有一个参数,即触发它的事件。

listener:Function — The listener function that processes the event. This function must accept an Event object as its only parameter and must return nothing, as this example shows:

function(evt:Event):void

Source



您可以通过让事件调用的函数调用另一个具有所需参数的函数来解决此问题:
timer.addEventListener(TimerEvent.TIMER, _saveChat);
function _saveChat(e:TimerEvent):void
{
    saveChat(arg, arg, arg);
}

function saveChat(arg1:type, arg2:type, arg3:type):void
{
    // Your logic.
}

您可以做的另一件事是创建一个扩展 flash.events.Event 的自定义事件类。并创建您需要的属性。
package
{
    import flash.events.Event;

    public class CustomEvent extends Event
    {
        // Your custom event 'types'.
        public static const SAVE_CHAT:String = "saveChat";

        // Your custom properties.
        public var username:String;
        public var chatBoxText:String;

        // Constructor.
        public function CustomEvent(type:String, bubbles:Boolean=false, cancelable:Boolean=false):void
        {
            super(type, bubbles, cancelable);
        }
    }
}

然后你可以使用定义的属性来调度它:
timer.addEventListener(TimerEvent.TIMER, _saveChat);
function _saveChat(e:TimerEvent):void
{
    var evt:CustomEvent = new CustomEvent(CustomEvent.SAVE_CHAT);

    evt.username = "Marty";
    evt.chatBoxText = "Custom events are easy.";

    dispatchEvent(evt);
}

并倾听它:
addEventListener(CustomEvent.SAVE_CHAT, saveChat);
function saveChat(e:CustomEvent):void
{
    trace(e.username + ": " + e.chatBoxText);
    // Output: Marty: Custom events are easy.
}

关于actionscript-3 - 如何将参数传递给 flex/actionscript 中的事件监听器函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6406957/

相关文章:

apache-flex - 有没有办法将另一个类的成员函数作为参数传递给as3中的函数?

actionscript-3 - AS3错误2025删除子项

flash - ActionScript 3 : get display object at pixel

flash - 我可以在 Electron.js 应用程序中捆绑 Pepper Flash 以在 2021 年以后运行 Flash 吗?

android - Adobe AIR 是否正在将 Flash 文件导出到手机?

apache-flex - Flex 开发的网页内容可以搜索到吗?

apache-flex - Adobe AIR 中的多个窗口

flash - AS3中匿名函数有什么用?

actionscript-3 - 分析 ActionScript-3 代码

flash - ActionScript - 缩小字体大小的文本字段