Web Analytics Made Easy -
StatCounter Help needed on array and buttons - CodingForum

Announcement

Collapse
No announcement yet.

Help needed on array and buttons

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • Help needed on array and buttons

    Hi,
    I'm new to this forum. I'm having problems with arrays in as3. Is it possible to load each array value to different buttons?

    For example, I have an object array with 10 different questions(not on stage. It's from a json file being pushed into an array as a object) and I have a page with 10 different buttons. I would like to click the different buttons and it will lead to the corresponding questions in the array.

    For eg.

    questionsArray:Array = new Array();
    buttonsArray:Array = new Array(button1,button2,etc....,button10);

    the json decoder has been used to decode my json file and it's working fine.
    the 10 questions has also been pushed into questions array.

    Items in buttonsArray are in the stage and are suppose to lead to their respective questions.
    i.e:button 1 leads to question 1.

    This could be done by adding a MouseEvent listener on every single button.But this will be very tedious and messy. It would also be difficult if there are too many questions to code for. So I was wondering if there is anyway, i could use the indexOf array or any other method to implement my buttons dynamically.

    Any help would be much appreciated!

    -hopelesscoder

  • #2
    Solution:
    • name each of your buttons by setting name property, e.g.:
      Code:
      button.name = "but1"
    • create a DisplayObjectContainer instance e.g.:
      Code:
      var container:DisplayObjectContainer = new DisplayObjectContainer();
      addChild(container);
    • add each of your button to the container e.g.:
      Code:
      for (iNo:Number = 1; iNo < buttonsArray.lenght; iNo++){
        var button:Button =  buttonsArray[i];
        button.name = "but" + iNo;//name the button
        button.y = iNo*30;// display one below the other
        container.addChild(button);
      }
    • add click listener to your container
      Code:
      function onButtonClick(event:MouseEvent):void{
        var button = event.target as Button;
        if(button){
          //use button.name to extract the question number on your own :P
        }
      }
      container.addEventListener("click", onButtonClick);
    Descript.org - lightweight JavaScript foundation framework

    Comment


    • #3
      thank you so much for your reply. I've tried your way and it works

      Comment

      Working...
      X