Yes, when you add the button's listener to a function within that object, of course only that object will receive the event. When you call addEventListener
with the highlightMe
function, you pass a reference to the highlightMe
function within the current scope. That means that the private function within that class is referenced. But that function is different for each new instance of the class.
In OOP each object works for itself and doesn't know anything about the parents, so one link button should not be able to know that there are other link buttons beside itself and what those buttons do. Instead the parent knows that there are X different link buttons, each working alone, but managed by the parent to work together. In that sense, when working with events, one should always leave the event handling in the parent object – except your custom class has default handlers that keep a standard procedure working (like changing appearance on mouse over etc), or when you have custom events that encapsulate other events.
As such the correct way to deal with it, is to have a single event handler in the parent class (where you instantiate the buttons) which then also is able to identify which button the event is related to.
Example
public class SomeParent extends Sprite
{
public function SomeParent ()
{
var btn:Button;
for ( var i:uint = 0; i < 100; i++ )
{
btn = new Button();
btn.label = 'Button ' + i;
btn.addEventListener( MouseEvent.CLICK, clickHandler );
this.addChild( btn );
}
}
private function clickHandler ( event:MouseEvent ):void
{
var btn:Button = event.eventTarget as Button;
trace( 'Button with id ' + this.getChildIndex( btn ) + ' and label "' + btn.label + '" was pressed.' );
}
}