2 Replies Latest reply on Aug 20, 2007 10:16 AM by SymTsb

    buttons with repeated AS

      I have made four buttons.

      Each buttons shall have a AS3 code, doing something.

      Instead of writing the same code for every buttons, I want to make a "for" loop and activate eventhandler for button1 - up to button4. But something goes wrong, can someone please take a look. Heres my code:


      for (var count:Number = 1; count<5; count++) {

      this["button" + count].addEventListener(MouseEvent.MOUSE_OVER, overHandler);
      this["button" + count].addEventListener(MouseEvent.MOUSE_OUT, outHandler);
      this["button" + count].addEventListener(MouseEvent.CLICK, clickHandler);

      function overHandler(event:MouseEvent):void {
      TweenLite.to(this["button"+count], 0.5, {scaleX:1.3, scaleY:1.3});
      function clickHandler(event:MouseEvent):void {
      TweenLite.to(this["button"+count], 0, {scaleX:1.3, scaleY:1.3, alpha:0.5});
      TweenLite.to(this["button"+count], 0.2, {alpha:1, delay:0.2, overwrite:false});
      function outHandler(event:MouseEvent):void {
      TweenLite.to(this["button"+count], 0.5, {scaleX:1, scaleY:1, alpha:1});

        • 1. Re: buttons with repeated AS
          kglad Adobe Community Professional & MVP
          when your button events occur count is 4. ie, your for-loop has completed and after it's completed count is at its last value.

          instead of

          this["button" + count] // in your event listeners, use:

          event.currentTarget // note: you may need to cast event.currentTarget as a button or object: Button(event.currentTarget)

          • 2. Re: buttons with repeated AS
            SymTsb Level 2
            Simply in terms of good coding practice, move the actual function handlers outside of your for loop. All the for loop needs to do is add the event listeners themselves. Redeclaring the functions X times is just a waste of resources. As long as you make the change that kglad suggested first, you'll be in great shape.