2

I have the following function in Flex 4:

protected function initEventHandlers():void
        {
            imageContainer.addEventListener(DragEvent.DRAG_ENTER, acceptDrag);
            imageContainer.addEventListener(DragEvent.DRAG_DROP, handleDrop);

            img_1.addEventListener(MouseEvent.MOUSE_DOWN, handleDrag);
            img_2.addEventListener(MouseEvent.MOUSE_DOWN, handleDrag);
            img_3.addEventListener(MouseEvent.MOUSE_DOWN, handleDrag);
            img_4.addEventListener(MouseEvent.MOUSE_DOWN, handleDrag);
        }

I didn't like the look of this code though. The four images are declared inside my application as follows:

<s:HGroup y="10" width="650" horizontalAlign="center" horizontalCenter="6">
        <s:Image width="80" height="80" source="images/1.jpg" id="img_1" />     
        <s:Image width="80" height="80" source="images/2.jpg" id="img_2" />
        <s:Image width="80" height="80" source="images/3.jpeg" id="img_3" />
        <s:Image width="80" height="80" source="images/4.jpg" id="img_4" />
</s:HGroup>

Isn't there a way to loop over each image in the hgroup and add the eventhandler?

Something like this:

for(image in hgroup) { 
    image.addEventlistener(MouseEvent.MOUSE_DOWN, handleDrag); 

}

 My teacher told me this isn't possible but in case of 10+ images, I can't imagine doing it for every image separately. There has to be a better way to do this, no?

Thanks in advance!

Joris Ooms
  • 11,880
  • 17
  • 67
  • 124
  • 1
    Seems like your teacher gave you the crappiest answer since... ever :D The simple proof can be found in RIAStars' post – Dennis Jaamann Oct 21 '11 at 15:56
  • 1
    Furthermore your teacher shouldn't be allowed to teach Flex, this is really basic stuff.... I would be worried – JTtheGeek Oct 21 '11 at 18:07
  • IMO, it's not possible for most people to both be an active developer on challenging projects _and_ teach. So, by default, most teachers are those who are not doing real-world development work. – Amy Blankenship Dec 14 '11 at 13:37

1 Answers1

6

Your teacher is wrong!

Give the HGroup an id (e.g. imageGroup).

Then do this:

var numElements:int = imageGroup.numElements;
for (var i:int = 0; i<numElements; i++) {
    var image:Image= imageGroup.getElementAt(i) as Image;
    if (image) image.addEventlistener(MouseEvent.MOUSE_DOWN, handleDrag); 
}
RIAstar
  • 11,912
  • 20
  • 37