views:

159

answers:

3

Im trying to create a loop of items like this...

    for each (var btn:Object in ViewButtonData)
    {
      // build element
      var box:HBox = new HBox();
      box.styleName = "lefttab";
      box.width = "100%";
      box.addEventListener("rollOver", HoverTab(btn.id, 1));
      box.addEventListener("rollOut", HoverTab(btn.id, 0));

      // add element to list
    }

I would like to pass in current HBox to the 'HoverTab' function. Is there a way to do that?

+1  A: 

The HBox should automatically be available in the event handler via event.currentTarget.

James Ward
+1  A: 
box.addEventListener("rollOver", hoverTab(btn.id, 1));
box.addEventListener("rollOut", hoverTab(btn.id, 0));

This won't work unless hoverTab is a function that returns a function that takes an event as its sole argument. Replace it with:

box.addEventListener("rollOver", hoverTab);
box.addEventListener("rollOut", rollOutTab);

And as James mentioned, you'll get HBox from event.currentTarget

function hoverTab(event:MouseEvent):void
{
   var box:HBox = HBox(event.currentTarget);
}

To get btn.id inside hoverTab, store HBoxes and btn.ids into two arrays from the for-each loop. Now you can get the index of HBox using indexOf method - btn.id will be at the same index in its array.

var boxes:Array = [];
var ids:Array = [];
for each (var btn:Object in ViewButtonData)
{
  // build element
  var box:HBox = new HBox();
  boxes.push(box);
  ids.push(btn.id);
  box.addEventListener(MouseEvent.ROLL_OVER, hoverTab);
  box.addEventListener(MouseEvent.ROLL_OUT, rollOutTab);

  // add element to list
}
function hoverTab(event:MouseEvent):void
{
   var box:HBox = HBox(event.currentTarget);
   var btnid:Number = ids[boxes.indexOf(box)];
}

Alternatively, (since ActionScript allows different types in the same array), you can push them into the same array and read the btn.id as array[array.indexOf(box) + 1]

Amarghosh
+2  A: 

James Ward's comment is correct. You can just do:

function myHandler(event:Event):void {
    var myHBox:HBox = event.currentTarget as HBox;
}

That said, the answer to your question is:

box.addEventListener("rollOver", function(e:Event) { HoverTab(box, btn.id, 1); });

..spread out for more readability:

box.addEventListener("rollOver", 
                     function(e:Event) { 
                         HoverTab(box, btn.id, 1); 
                     }
                    );
Ender