Search code examples
actionscript-3flasheventslisteners

AS3 Using Many Event Listeners Causing Problems, How to Reduce?


Confusing title, my bad.

Basically, I have a list of names. Looping through, I add a MovieClip, Set 2 properties to it, the name, and an ID. The MovieClip is at the same time made to function as a button and I add 4 listeners, mouse up, over, down, or out. I do this with every name. The function each one is set to is the same.

EX: enemyButton[i].addEventListener(MouseEvent.MOUSE_UP, mouseUpHandler);

The enemyID turns up "not valid property," time to time when I click, it doesn't crash at all, but sometimes I have to hit the button a few times.

I have narrowed the problem down to having to be caused by the listeners.

The function as simple as:

EX: function mouseUpHandler(e:MouseEvent):void { enemySelected(e.target.enemyID); }

My question is, is too many listeners likely to be the problem? and how can I reduce them?

Here's a snippet of the loop:

var C:Class = Class(getDefinitionByName(enemies[i]));
var c:* = new C(); 
c.gotoAndStop(1);
enemyButton[i].enemyID = i;
c.name = "select" + i;
c.enemyID = i;
trace(c.enemyID);
enemyButton[i].addChild(c);
enemyScroll.addChild(enemyButton[i]);
enemyButton[i].enemyName.text = info[i][Const.NAME];
enemyButton[i].setChildIndex(enemyButton[i].getChildByName("enemyName"), enemyButton[i].numChildren-1);

Thanks.


Solution

  • If enemyButton is a MovieClip (created via attachMovie, maybe) and not strongly typed as a EnemyButton class, then the ID property becomes dynamic. In this situation, if your list of names contains incorrect data (missing ID field, maybe), then the ID property will remain undefined on some instances of the MovieClip.

    You can check the list of data used to generate movie clips. You can run into the same error if you have blank lines in your data.

    This has nothing to do with event listeners.