3 Replies Latest reply on Jan 23, 2009 12:12 PM by Garyl Woolworth

    Counting instances

      Hi, was wondering if anyone could give me some advice on this...
      I have a custom component "MyObject" which can be added multiple times to the stage via addChild. A user can add as many of these "MyObjects" as they want. They can also delete them

      I would like a way to find the total number of instances of this component at any point. Right now I'm adding each component to the stage and also to an array. Trouble is it gets messy when I am trying to add and delete MyObjects and also keep the array up to date.

      Basically I would like a way to just count how many instances of this component are currently displayed.

      Thanks a lot for any help at all
        • 1. Re: Counting instances
          Garyl Woolworth Level 1
          Honestly there are a ton of different ways to do this and it all really depends on what other aspects you need to do with MyObjects of where it becomes clear of which way is better then another. A pretty simple way of doing it is have a property within MyObject that sets it apart from all the other children like MyObject.childType = "spiffyChild" and then when you need the total number of them you could run through the containers children looking for that property.

          Another way you could go about it is through listeners using the childAdd and childRemoved events that get broadcasted from the container to maintain an array or collection of how many you have.

          A third way you could do it is change the layout structure so that all of your instances will always have their own container and nothing else, so then whenever you need a total you simple do container.numChildren.

          Like I said though any of these can get you a number it just all depends on the overlaying structure of your project on which way will fit best.
          • 2. Re: Counting instances
            chrun Level 1
            Thanks a lot for the answer, I know it's simple stuff but those little explanations are so useful (to me anyway!). Went for the third option in the end and it works great.
            • 3. Re: Counting instances
              Garyl Woolworth Level 1
              No problem, glad it worked.