1 Reply Latest reply on Jan 26, 2011 5:35 PM by Pappa_John

    Creating Functions in a Loop

    jordana309-36

      I am trying to create functions in a loop that will call a clickHandler for an unknown number of objects. The point is so that each object created will will have a click event handler, passing through a unique identifier for that object into the handler function. After looking at a lot of forum posts, this is what I thought would be easiest. Well, when I run it, I get the following error: "Cannot create property btn1ClickHandler on controlScreenMain." I need each function to be uniquely named because when I just attach an event handler to the buttons, then they would always overwrite the function created for the previous object in the loop, resulting in every button doing the exact same thing and passing the same values (whatever was last used to create the handler). My code:

       


      [CODE]

        protected var btns:Array = new Array();

       

        protected function btnsSetter():void

        {

          var groupLength:int = buttonGroup.numElements;
          var btn:Object;
          var btnNumber:int;
          var videoFileName:String = "";
          var handlerFunctionNamePrefix:String = "";
          for(var i:int=0; i<groupLength; i++)
          {

              //buttonGroup is an MXML group that dynamically loads objects and code elsewhere will create a button for each of them.
              if(buttonGroup.getElementAt(i) is ToggleButtonCustom)
              {
                  btn = buttonGroup.getElementAt(i);
                  btns.push(btn);
                  btnNumber = (btns.length - 1);
                  handlerFunctionNamePrefix = "btn" + (btnNumber);
                  this[handlerFunctionNamePrefix + "ClickHandler"] = new Function();
                 
                  /*(event:Event=null):void{
                      btns_clickHandler(btnNumber, btn.videoFileName)
                  }*/
              }
          }

       

      // A bunch of other conditional code

       

          for(i=0; i<btns.length; i++)
          {
              videoFileName = btns[i].videoFileName;
              handlerFunctionNamePrefix = "btn" + (i+1);
              btns[i].addEventListener(MouseEvent.CLICK, this[handlerFunctionNamePrefix + "ClickHandler"]);
          }

        } // End function btnsSetter

      [/CODE]

       

      I have gone through a lot of iterations now, and all fail. Any ideas? I'm shot for the day, so I'm sorry if the code above makes no sense. Thanks for your help!