【问题标题】:In AS3, load a text file into a string在 AS3 中,将文本文件加载到字符串中
【发布时间】:2014-12-31 14:53:49
【问题描述】:

我一直在尝试将文本文件加载到字符串变量中。名为text.txt 的文本文件包含successful。代码如下:

public class Main extends Sprite
{
    private var text:String = "text";
    private var textLoader:URLLoader = new URLLoader();

    public function Main() {
        textLoader.addEventListener(Event.COMPLETE, onLoaded);
        function onLoaded(e:Event):void {
            trace("Before 1: " + text); //output: text
            trace("Before 2: " + e.target.data); //output: successful
            text = e.target.data;
            trace("After 1: " + text); //output: successful - yay!!! it worked

        }

        textLoader.load(new URLRequest("text.txt"));

        trace("After 2: " + text); //output: text - what??? nothing happened??? but it just worked

    }

}

输出:

After 2: text Before 1: text Before 2: successful After 1: successful

【问题讨论】:

    标签: actionscript-3 asynchronous


    【解决方案1】:

    您正面临同步与异步的问题

    textLoader 在调度Event.COMPLETE 时异步调用函数onLoaded,而不是在textLoader.load 之后直接调用的"After 2"

    您必须记住的是textLoader.load 是非阻塞的,这意味着"After 2" 可能(您可以始终假设)在onLoaded 之前执行。

    如果在回答的这一点上您仍然感到困惑,我会说加载文件需要时间并且执行指令可能会随时间而变化,但通常比加载文件所需的时间要短得多(想象一下这个文件是 4go 大)。你无法预测会发生什么,也许磁盘已经很忙你可能需要等待!但是您可以利用这段宝贵的时间做一些完全独立于文本文件的其他事情,这就是为什么它有时由编程语言异步生成(例如php 同步加载文件)。

    下一步


    既然我已经解释了"After 2" 并不真正存在,你必须使用"After 1" 作为入口点,但没有什么可以帮助您创建一个名为 afterLoad 的函数,您可以像这样调用它

    public function Main() {
            textLoader.addEventListener(Event.COMPLETE, onLoaded);
    
            function onLoaded(e:Event):void {
                trace("Before 1: " + text); //output: text
                trace("Before 2: " + e.target.data); //output: successful
                text = e.target.data;
                afterLoad();
            }
    
            textLoader.load(new URLRequest("text.txt"));
        }
    
    
    }
    
    private function afterLoad():void {
        trace("After: " + text); // it should work now :)
    }
    

    【讨论】:

    • 那我该怎么办?
    • 但是我以后可以以及如何获取它(加载的文本)吗?
    • 重点是你必须通过afterLoad或者直接在onLoaded里面。唯一的选择是在 main 准备好时使用自定义事件进行调度,但这是多余的。您可以将afterLoad 重命名为MainWithDataLoaded,如果它可以帮助您了解这个问题的核心是什么。
    • 好的。我知道了。所以现在我将其余代码写入afterLoad() - MainWithDataLoaded() 而不是Main()
    猜你喜欢
    • 2015-04-05
    • 1970-01-01
    • 2023-03-13
    • 2023-01-11
    • 2016-04-01
    • 2021-04-26
    • 2021-04-30
    • 2018-10-09
    • 1970-01-01
    相关资源
    最近更新 更多