js_*_*js_ 0 flash actionscript callback event-listener actionscript-3
在回调函数中调用类的方法时,不能使用thisobject.
要调用该方法,在JavaScript中,我声明that的变量,分配this到that,并且使用that回调内部调用的方法this.
在动作脚本中,我是否必须像在javascript中那样做?
以下代码是that用于在回调内调用方法的示例.
动作中有更简单的方法吗?
class C {
private var that:C;
function C() {
that = this
}
public function f1():void {
var sp:Sprite = new Sprite;
sp.addEventListener(MouseEvent.CLICK, function():void {
this.f2(); // this doesn't work
that.f2(); // that works
});
}
public function f2():void {
trace('hello');
}
}
Run Code Online (Sandbox Code Playgroud)
如果将回调函数作为C类的方法,则可以访问this.
public class C
{
private function f1():void
{
var sp:Sprite = new Sprite();
sp.addEventListener(MouseEvent.CLICK, callback);
}
private function callback(event:MouseEvent):void
{
this.f2();
}
private function f2():void
{
trace("Hello World");
}
}
Run Code Online (Sandbox Code Playgroud)
现在this引用类C的实例,其范围是整个类.
这是另一种方法:
package some.package {
class SomeSprite extends Sprite {
public function f1():void
{
var sprite1:Sprite = new Sprite;
sprite1.addEventListener(MouseEvent.CLICK,
(new Closure(f2, this, ["Hello"], sprite1).handler));
var sprite2:Sprite = new Sprite;
sprite2.addEventListener(MouseEvent.CLICK,
(new Closure(f2, this, ["Bye Bye"], sprite2).handler));
}
private function f2(message:String):void
{
trace(message);
}
}
}
class Closure {
public var callback:Function;
public var thisObj:Object;
public var params:Array;
public var dispatcher:IEventDispatcher;
public var cleanAfterCallback:Boolean = true;
function Closure(callback:Function, thisObj:Object,
params:Array, dispatcher:IEventDispatcher)
{
this.callback = callback;
this.thisObj = thisObj;
this.params = params;
this.dispatcher = dispatcher;
}
public function handler(e:Event):void
{
callback.apply(thisObj, params);
if (cleanAfterCallback)
dispatcher.removeEventListener(e.type, eventHandler)
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
910 次 |
| 最近记录: |