我有这个班级('Scheduler.as'):
package
{
import flash.events.TimerEvent;
import flash.utils.Timer;
public class Scheduler
{
private var m_tmr:Timer = null;
private var m_the_this:* = null;
private var m_function:Function = null;
private var m_args:Array = null;
public function Scheduler(the_this:*, f:Function, interval:int, args:Array = null)
{
this.m_the_this = the_this;
this.m_function = f;
this.m_args = args;
if (this.m_args.length == 0)
this.m_args = null;
this.m_tmr = new Timer(interval, 1);
this.m_tmr.addEventListener(TimerEvent.TIMER, on_timer);
this.m_tmr.start();
}
private function on_timer(e:TimerEvent):void
{
if (this.m_args == null)
this.m_function.call(this.m_the_this);
else
this.m_function.call(this.m_the_this, this.m_args);
}
public static function schedule_call(the_this:*, f:Function, interval:int, ...args):Scheduler
{
return new Scheduler(the_this, f, interval, args);
}
}
}
这是一个使用它的AS3 FlashDevelop应用程序('Main.as'):
package
{
import flash.display.Sprite;
import flash.events.Event;
public class Main extends Sprite
{
public function Main():void
{
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}
private function init(e:Event = null):void
{
removeEventListener(Event.ADDED_TO_STAGE, init);
// entry point
Scheduler.schedule_call(this, this.test_func_NO_PARAMS, 0);
Scheduler.schedule_call(this, this.test_func_ONE_PARAM, 0, 123);
Scheduler.schedule_call(this, this.test_func_TWO_PARAMS, 0, "HELLO", "WORLD");
}
private function test_func_NO_PARAMS():void
{
trace("No params was called successfully!");
}
private function test_func_ONE_PARAM(some_number:int):void
{
trace("One param was called successfully! 'some_number' = " + some_number);
}
private function test_func_TWO_PARAMS(stringA:String, stringB:String):void
{
trace("Two params was called successfully! 'stringA' = " + stringA + ", 'stringB' = " + stringB);
}
}
}
正如您在测试运行中看到的前两个调用正常,调用不带参数的函数和的函数采用一个参数。
问题是当我需要传递多个参数时!
解决问题:
嗯,我知道如果我能够保留 ...args
原样,并将其传递给this.m_function.call
来电,就会解决问题。< / p>
另一种方式,可能是某种foreach
循环会在时间到来时提供指定的...args
,再次,我将如何引用/传递它? / p>
这里必须有一个很好的技巧才能让它发挥作用,欢迎你和我一起出汗!
答案 0 :(得分:1)
尝试更改此行:
this.m_function.call(this.m_the_this, this.m_args);
到此:
this.m_function.apply(this.m_the_this, this.m_args);
apply
将参数作为列表而不是单个数组传递给应用函数(效果与编写the_function(arg[0],arg[1],arg[N])
相同)。
编辑:
也许我不理解你的问题,但这个简化的代码示例工作正常(我没有使用Timer,我没有构建任何实例,但我认为这里的主要内容是如何应用工作;采取一组参数,并将它们作为变量参数列表传递给调用函数):
private function arg0():void {
trace("arg0");
}
private function arg1(a:*):void {
trace("arg1");
}
private function arg2(a:*,b:*):void {
trace("arg2");
}
private function arg3(a:*,b:*,c:*):void {
trace("arg3");
}
private function test():void {
schedule_call(this,arg0,10);
schedule_call(this,arg1,10,1);
schedule_call(this,arg2,10,1,2);
schedule_call(this,arg3,10,1,2,3);
}
public function schedule_call(the_this:*, f:Function, interval:int, ...args):void
{
var m_args:Array = args;
f.apply(the_this, m_args);
}