2013-02-16 55 views
0

我有兩個功能在我的AS3方案,一個火災時,寬度和高度的變化:whitout具有正確的參數調用某些功能

stage.addEventListener(Event.RESIZE, resizeListener); 
function resizeListener (e:Event):void { 
//some commands 
} 

,第二個觸發一個毫秒數傳:

var myTimer:Timer = new Timer(clockUpdate, 0); 
myTimer.addEventListener(TimerEvent.TIMER, updateData); 
myTimer.start(); 

function updateData(e:TimerEvent):void { 
    trace("AUTOUPDATE"); 
    trace(e); 
} 

我需要手動觸發這些功能,可以說當用戶按下一個按鈕,但我不知道什麼參數,我必須發送他們時,他們被手動調用。

我只是嘗試resizeListener()和updateData(),但當然它失敗了,要求我參數。

回答

3

通過提供默認值,可以使函數中的參數可選。這是把你的兩個函數上方,使事件參數可選的例子:

function resizeListener(e:Event = null):void { 
    //some commands 
} 

function updateData(e:TimerEvent = null):void { 
    trace("AUTOUPDATE"); 
    trace(e); 
} 

通話,例如,resizeListener()現在執行的功能和e值將默認到null

1

使事件參數可選,resizeListener(e:Event=null),正如在walkietokyo的答案中一樣,是一個非常有效且常常方便的解決方案。另一種選擇是將你想要做的事情放在一個單獨的函數中,而不需要在事件處理程序和其他任何地方調用事件。因此,假設您想調整大小的方法是重新排列布局,並且您還希望在初始化時或單擊按鈕或任何時候執行相同的佈局設置,您可以執行以下操作是這樣的:

stage.addEventListener(Event.RESIZE, resizeListener); 
function resizeListener(e:Event):void { 
    rearrangeLayout(); 
} 

function rearrangeLayout():void { 
    // The actual rearrangement goes here, instead of in resizeListener. This can be called from anywhere. 
} 

哪種方式做到這一點可能是一個品味的問題,也可從個別情況而異,果然,無論是工作正常。

在事件處理函數和另一個函數中分離事物的好處是,不會出現這樣一種情況,您必須檢查e:Event參數是否爲null。換句話說,在事件處理程序中,您將擁有依賴於事件(如果有的話)的代碼,以及與更一般函數(而非事件處理程序)中的事件無關的代碼。

所以在更一般和原理的情況下,該結構將是這樣的:

addEventListener(Event.SOME_EVENT, eventListener); 
function eventListener(e:Event):void { 
    // Code that needs the Event parameter goes here (if any). 
    // Call other function(s), for the stuff that needs to be done when the event happens. 
    otherFunction(); 
} 

function otherFunction():void { 
    // Stuff that is not dependent on the Event object goes here, an can be called from anywhere. 
} 
相關問題