4 Replies Latest reply on Jun 10, 2007 5:32 AM by mxc4

    Is there an equivalent to getById()

      Is there a similar funtion in flex/actionscript?
      Basically I get a text representation of the id and want to either do variable.text where variable is "txtUsername" id or to be able to ge getById()

        • 1. Re: Is there an equivalent to getById()
          mxc4 Level 1
          ok -- I read that one can do something like this["componentId"] but this doesn't seem to work. :(
          • 2. Re: Is there an equivalent to getById()
            ctzn99 Level 1
            If the control that you want is in a container (or even just in the "application" container) you can use the getChildren which returns an array of DisplayObjects. The id property is available to each control at the display object level so then you can iterate through each item in your array looking for a matching ID. Essentially you're building your own getByID()... here's a sample script bit assuming that you have a canvas or panel called "controlContainer"

            private function getControlByID(searchID:String):DisplayObject
            for each(var control:DisplayObject in controlContainer.getChildren())
            if (control.id == searchID)
            return control; // return immediately and stop searching.
            // if the above loop doesn't find a match.
            return null;

            You could also add a bit of extra logic if you only wanted to return certain controls (for example labels only) by adding the following once a matching ID is found.
            if (control is a Label)
            return control;


            • 3. Is there an equivalent to getById()
              ctzn99 Level 1

              Well it seems i just learned something. While the example i provided above should work for you just fine using the indexer of an object works like you aluded to in your second post (and is less work). I.e. this["itemID"]. I didn't know this and for some reason thought i would try it out.

              this will also work assuming the following function is a click event for a button and that there is a button in the application called "myButton".

              private function button_clicked():void
              var object:DisplayObject = this["mybutton"];
              var button:Button = Button(object);
              button.label = "label changed";


              * I can post a full working sample if you need it.
              • 4. Re: Is there an equivalent to getById()
                mxc4 Level 1
                Hi ctzn999,

                I found that the this["string representation of id "] did not work for me when the elements are created dynamically at run time. I had to create a dictionary object and put all the components in there and use the id as the key value. It might very well be that I don't know enough of flex yet and their is an easier way. An example of what I did can be found at our software development company's blog