dcsimg
A Flash Developer Resource Site

Results 1 to 3 of 3

Thread: sending a var between functions (but using Timer)

Hybrid View

  1. #1
    aidanmack.co.uk
    Join Date
    Dec 2001
    Location
    York, UK
    Posts
    400

    sending a var between functions (but using Timer)

    Hi guys im using the timer to triger a second function from the top one.
    But how do i sent a variable from the top function down to second one??

    Code:
    public function wait_for_flv() {
         var poo = "plop";
         var myTimer:Timer = new Timer(5000, 1);
          myTimer.addEventListener("timer",attach_menu);
          myTimer.start();
    }
    
    
    public function attach_menu(event:TimerEvent):void {
    
    	trace("plop");			
    }
    The above code works fine, but how would you send the var poo down to attached_menu function??

    Tar
    Aidan

  2. #2
    Will moderate for beer
    Join Date
    Apr 2007
    Location
    Austin, TX
    Posts
    6,801
    You can't.

    But you do have alternatives. The easiest way is to put poo in a scope which is accessible to both wait_for_flv and attach_menu. Simply move it up to the class level:
    Code:
    private var poo;
    public function wait_for_flv() {
         poo = "plop";
         var myTimer:Timer = new Timer(5000, 1);
          myTimer.addEventListener("timer",attach_menu);
          myTimer.start();
    }
    
    public function attach_menu(event:TimerEvent):void {
    
    	trace(poo);			
    }
    This is kind of clumsy, but not terrible.

    A second choice would be to create an anonymous thunk function as an event handler.
    Code:
    public function wait_for_flv() {
         var poo = "plop";
         var myTimer:Timer = new Timer(5000, 1);
          myTimer.addEventListener("timer",makeAttachMenuListener(poo));
          myTimer.start();
    }
    
    private function makeAttachMenuListener(poo:String):Function{
      return function(event:Event):void{
        attach_menu(poo);
      }
    }
    
    public function attach_menu(p:String):void {
    
    	trace(p);			
    }
    This technique is more sophisticated, but be VERY aware that creating anonymous functions to use as event listeners is a fast-track to memory leaks unless you are very careful. This is also not a true thunk, as it takes an argument, but that's merely a technicality.

  3. #3
    aidanmack.co.uk
    Join Date
    Dec 2001
    Location
    York, UK
    Posts
    400
    Thanks for explaining that to me 5tons!
    Think i will stick with the private var looks a bit easyier!

    Thanks again
    Aidan

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  




Click Here to Expand Forum to Full Width

HTML5 Development Center