Using a For loop with an array and addEventListener
I have this map I'm creating in Flash. You click on a state, then you can click on an icon to view a tooltip/popup of some information. What I was trying to do was instead of creating new functions and event listeners for every different icon is to use a for loop...but it's not going so well. I haven't touched AS in a long time so bear with me :)
var ToolTipMC = map.toolTip;
ToolTipMC.alpha = 0;
var places:Array = new Array();
places = [ "map.p开发者_开发知识库aulsens", "map.plutonic", "map.jundee", "map.wiluna", "map.darlot", "map.lawers", "map.gwaliaDeeps", "map.sunriseDam", "map.marvelLoch" ];
function enableToolTips( event:MouseEvent ):void {
ToolTipMC.x = places[ i ].x + 10;
ToolTipMC.y = places[ i ].y - ( ToolTipMC.height - 9 );
Tweener.addTween( ToolTipMC, { y: ToolTipMC.y + 5, alpha: 1, transition: "easeInOutExpo", time: 0.3 } );
ToolTipMC.toolTipTextField.text = "It worked!";
trace( "Mouse Over" );
}
function disableToolTips( event:MouseEvent ):void {
Tweener.addTween( ToolTipMC, { alpha: 0, transition: "easeInOutExpo", time: 0.3 } );
trace( "Mouse Out" );
}
for( var i:uint = 0; i < places.length; i++ ) {
places[ i ].addEventListener( MouseEvent.MOUSE_OVER, enableToolTips );
places[ i ].addEventListener( MouseEvent.MOUSE_OUT, disableToolTips );
}
The items in the array are instance names and I'm using the Tweener class(es).
The following throws an Output error of
TypeError: Error #1006: value is not a function
and is stopping at the
places[ i ].addEventListener( MouseEvent.MOUSE_OVER, enableToolTips );
So from this I can gather that it's having problems parsing the array values through to the event listener, but that's as far as I got :). Could anyone please help me with my dilema?
I see a few things that might be causing the problem:
- Places are "strings", not IEventDispatchers
- Not sure you can run a for-loop outside of a function, try wrapping it in a function.
Here's what it might look like.
function addListeners():void {
for( var i:uint = 0; i < places.length; i++ ) {
(places[ i ] as IEventDispatcher).addEventListener( MouseEvent.MOUSE_OVER, enableToolTips );
(places[ i ] as IEventDispatcher).addEventListener( MouseEvent.MOUSE_OUT, disableToolTips );
}
}
You'd have to convert places
to an Array of IEventDispatchers, maybe map items or whatever you're doing, some DisplayObject.
Hope that helps!
Following on from viatropos's answer - I assume you want to access the "place" with your tooltip that sent the event? You can do this using event.target
:
function enableToolTips( event:MouseEvent ):void {
var place:DisplayObject = DisplayObject(event.target);
ToolTipMC.x = place.x + 10;
ToolTipMC.y = place.y - ( ToolTipMC.height - 9 );
//the rest of your function...
}
(I'm also guessing that your "places" are movieclips placed on the stage - hence the cast to DisplayObject
)
精彩评论