title: Flex: assigning events to dynamically created buttons
body: <p>My app has buttons that users press to insert predefined strings into a textarea. I'm now making it load in the button values dynamically so users can define their own buttons.</p>
  
  <p>I'm using a buttons.txt which contains a different label on each line (button1, button2, button3 etc). I loop through the text file and add the buttons to a group. This all works, but now the hard part. How can I assign an eventlistener to these buttons so that they output text to the screen?</p>
  
  <pre><code>protected function view1_viewActivateHandler(event:ViewNavigatorEvent):void
          {
              var path:File = File.documentsDirectory.resolvePath("buttons.txt");
              myTextLoader.load(new URLRequest("file://" +path.nativePath));
              myTextLoader.addEventListener(Event.COMPLETE, onLoaded);
              trace(path.nativePath); // Traces correct file path
  
              mainTextField.addEventListener(SoftKeyboardEvent.SOFT_KEYBOARD_ACTIVATE, resizeTextField);
              if(data!=null){
                  mainTextField.text = data.toString();
              }else{
                  mainTextField.text = tags;
              }
          }
  
          protected function onLoaded(e:Event):void {
              var myArrayOfLines:Array = e.target.data.split(/\n/);
              var tempBtn:Button;
              trace(myArrayOfLines[0]);
              for(var i:Number = 0;i &lt; myArrayOfLines.length;i++){
                  tempBtn = new Button();
                  tempBtn.label = myArrayOfLines[i];
                  btnArray.push(tempBtn);
                  group.addElement(btnArray[i]);
              }
          }
  </code></pre>
  
  <p><strong>EDIT</strong></p>
  
  <pre><code>    protected function onLoaded(e:Event):void {
                  var myArrayOfLines:Array = e.target.data.split(/\n/);
                  var tempBtn:Button;
  
                  for(var i:Number = 0;i &lt; myArrayOfLines.length;i++){
                      var j:Number = i+1;
                      tempBtn = new Button();
                      tempBtn.id = "btn" + i;
                      tempBtn.addEventListener(MouseEvent.CLICK, function(evt:MouseEvent):void{
                          var index:uint = parseInt(evt.currentTarget.id.replace("btn", ""));
                                      //TextArea code will go here
  
  trace(text); // Traces null
                      });
                      tempBtn.label = myArrayOfLines[i];
                      btnArray.push(tempBtn);
                      group.addElement(btnArray[i]);
                  }
              }
  
  
  buttons.txt
       button1_label
      "Hello"
      button2_label
      "Goodbye"
      button3_label
      "Come again"
  </code></pre>