Log in

View Full Version : Arrays and onPress weirdness. Can't figure this out.



jlizarraga
01-06-2009, 11:49 PM
Simple test case: http://redesign1.autofusion.com/main/flash/scroller_new_v3.swf

I'm trying to assign onRollOver, onRollOut, and onPress event listeners to an array of movie clips that are acting as buttons, like so:


var gTabs:Array = [this.tabsAll, this.tabsPickup, this.tabsSedan, this.tabsHatchback, this.tabsCoupe, this.tabsConvertible, this.tabsCrossover, this.tabsVan, this.tabsSUV, this.tabsMinivan];

function someFunction():Void {
for (var i=0; i<gTabs.length; i++) {
var oName = gTabs[i]._name;
gTabs[i].onRollOver = function():Void {
this.gotoAndStop(2);
};
gTabs[i].onRollOut = function():Void {
this.gotoAndStop(1);
};
gTabs[i].onPress = function():Void {
_root.test_txt.text = oName;
};
}
}

As you can see from the demo, each tab correctly receives its rollOver and rollOut listeners; highlighting on mouseover as they should.

Now click a tab. The name of the tab (for example, "tabsAll" or "tabsCoupe") is supposed to show up. Instead, no matter which tab you click, "tabsMinivan" shows up.

Can anyone point me in the right direction? Why does oName get overwritten, and how can I avoid this behavior?

Medyman
01-07-2009, 03:16 PM
Hey jlizarraga...

This is fairly easy fix. You're making an assumption that I see many people mistakenly make. The purpose of your code is to assign event listeners to certain objects. Once they're assigned, it doesn't get run again.

So, when you say var oName = gTabs[i]._name;, oName does equal the value of the MC currently being looped. So for those tiny moments between when "Pickup" is activated and "Sedan" is activated, oName does indeed equal "tabsPickup". But, then the loop runs again and resets the variable. If you do a trace, you'll see that this is true.

The problem is that there is only one instance of the variable and multiple movieclips. So, you need to somehow attach the information to the movieclip. How do you do this? Try the code below:


var gTabs:Array = [this.tabsAll, this.tabsPickup, this.tabsSedan, this.tabsHatchback, this.tabsCoupe, this.tabsConvertible, this.tabsCrossover, this.tabsVan, this.tabsSUV, this.tabsMinivan];

function someFunction():Void {
for (var i=0; i<gTabs.length; i++) {
gTabs[i].oName = gTabs[i]._name;
gTabs[i].onRollOver = function():Void {
this.gotoAndStop(2);
};
gTabs[i].onRollOut = function():Void {
this.gotoAndStop(1);
};
gTabs[i].onPress = function():Void {
_root.test_txt.text = this.oName;
};
}
}

Now, you're attaching each item's name to the movieclip itself and then calling it independently of the loop.

jlizarraga
01-07-2009, 09:21 PM
Thanks Medyman!