如何在Actionscript中使用回调

时间:2012-04-17 00:37:23

标签: flex actionscript

所以我想说我有以下代码:

public function first(text:String):String {
   _text = text;
   dispatchEvent(event);

   //Want this statement to return the value of _text
   //after handler has finished transforming text.
   return _text;
}

//handles the event
public function handler(event:Event):void {
   //does things, then changes the value of _text
   _text = "next text that first needs to return";
}

如何确定方法(第一个)在被(处理程序)转换后返回正确的_text值?

提前谢谢!

1 个答案:

答案 0 :(得分:0)

由于ActionScript是单线程语言而事件处理程序不返回值,因此假设如果_text在包范围内是可变的,则代码将起作用。下一个代码没有多大意义,但是如果你从另一个类调用first函数它可能是有用的

package
{
    import flash.display.Sprite;
    import flash.events.Event;


    public class EventTest extends Sprite
    {
        public function EventTest()
        {
            addEventListener("sliceText", sliceHandler);

            //will be Some
            var newText:String = first("SomeText");
            trace(newText);
        }

        private var _text:String;

        public function first(text:String):String
        {
            _text = text;

            dispatchEvent(new Event("sliceText"));

            return _text;
        }

        protected function sliceHandler(event:Event):void
        {
            //let's slice text to be more valuable
            _text = _text.slice(0,4);
        }

    }
}