2

타이머에 매개 변수가있는 함수를 첨부하려하지만 "관련없는 함수 유형"이이 문제를 해결할 수있는 방법이 있습니까 ??Flash, ActionScript 3 : 매개 변수가있는 함수를 EventListener에 어떻게 제공합니까?

코드 예제 :

var redoTimer:Timer = new Timer(50); 

redoTimer.addEventListener(TimerEvent.TIMER, saySomething("helloo")); 
redoTimer.start(); 

이 늘 제대로 작동하지만 인수를 전달하는 방법이 ???

감사 Matthy

답변

3

당신은 정말 할 수없는 가장 가까운 상응하는 자신의 기능을 래핑하는 작은 인라인 함수를 사용하여이 될 것이라고 다음 addEventListener 기능

var redoTimer:Timer = new Timer(50); 

redoTimer.addEventListener(TimerEvent.TIMER, function(e:Event):void { saySomething("helloo") }); 
redoTimer.start(); 
+0

중첩 된 익명 함수를 반환하는 함수와 더 비슷합니다 (내 게시물 참조). – Pup

3

second parameter해야한다 함수. 실제로 코드는 saySomething("helloo") 메서드를 실행하고 반환 값을 addEventListener에 대한 두 번째 매개 변수로 사용하려고하므로 오류가 발생합니다.

또한 이벤트 수신기 함수는 flash.events.Event 유형의 하나의 인수 만 허용해야합니다. 하지만 코드에서 명시 적으로 호출하려는 경우 선택적 인수를 기본값으로 가질 수 있습니다.

0

로터리 어프로치로 가능합니다. 이벤트 처리기의 경우 중첩 익명 함수를 반환하는 함수를 사용하십시오.

private var textFieldA:TextField = new TextField; 
private var textFieldB:TextField = new TextField; 

public function setParameterizedTextWhenTextFieldsAreClicked():void { 
    addChild(textFieldA); 
    textFieldA.text = 'Text field A'; 
    textFieldA.addEventListener(MouseEvent.CLICK, showCustomMessage("One")); 

    addChild(textFieldB); 
    textFieldB.text = 'Text field B'; 
    textFieldB.y = 20; 
    textFieldB.addEventListener(MouseEvent.CLICK, showCustomMessage("Two")); 
    // NOTE: We must use strongly referenced listeners because weakly referenced 
    // listeners **will get garbage collected** because we're returning 
    // an anonymous function, which gets defined in the global namespace and 
    // thus, the garbage collector does not have anything pointing to it. 
} 

private function showCustomMessage (message:String):Function { 
    // NOTE: You can store the following function to a class variable 
    // to keep it in memory, which would let you use weakly referenced 
    // listeners when using this as an event handler. Many people 
    // would find that awkward. I would discourage that. 
    return function (e:MouseEvent):void { 
     var textField:TextField = e.target as TextField; 
     textField.text = message; // "message" argument is available because 
            // this function's scope is kept in memory. 
    } 
} 

익명의 함수를 사용하고 함수 범위를 메모리에 유지하면 가비지 수집이 복잡해집니다.

0

즉시 사용 가능한 :이 고대 퍼즐을 해결하기 위해 우아한 코드 2 줄만 추가로 필요합니다.

stage.addEventListener(MouseEvent.CLICK, onClick(true, 123, 4.56, "string")); 
function onClick(b:Boolean, i:int, n:Number, s:String):Function { 
    return function(e:MouseEvent):void { 
    trace("Received " + b + ", " + i + ", " + n + " and " + s + "."); 
    }; 
}