View Full Version : Dynamic Linkbuttons

12-31-2009, 09:41 PM
I've made the jump from as2 (yes its been awhile since ive touched this) to flex.
Previous i was able to do something like (i know this isnt exact but you can see what i am attempting to do)
for(x = 0;x<10;x++)
this['buttonName' + x] = new LinkButton();
this['buttonName' + x].label = details[x];
this['buttonName' + x].addEventListener();

This no longer will work because i cannot create dynamic variable names (or at least im not smart enough to know how to yet)

I am loading in data externally and i need to create a link button for each item loaded in.

for(x = 0;x<10;x++)
var linkButton:LinkButton = new LinkButton();
linkButton.label = companyDetails[x];
linkButton.addEventListener(MouseEvent.CLICK, function (e:MouseEvent):void {
companySelected(e, x);

This works fine in that it creates the 10 buttons as desired but when x gets passed it will always be 9. In flash it would pass as the value of x at time of creation because a separate instance of x is created.

Anyways i need to be able to create X linkbuttons and then have each of those linkButtons pass something unique into the event. Hope this makes sense.

01-02-2010, 10:38 PM
LinkButton has a property called data which is just a generic Object. You should be able to store the value of x in this property when you create the LinkButton and do something like this:

// Begin code block
var lb:LinkButton;

for (var x:int = 0; x < 10; x++)
// Create a new button
lb = new LinkButton();

// Set the button's label
lb.label = companyDetails[x];

// Set the button's data to the value of x
lb.data = x;

// Add MouseEvent.CLICK listener
lb.addEventListener(MouseEvent.CLICK, onLinkButtonClick);

// Add the LinkButton to a container

// End code block

// ... some other crap goes here

// Event handler

private function onLinkButtonClick(e:MouseEvent):void
// The LinkButton that was clicked
var currentTarget:LinkButton = e.currentTarget as LinkButton;

// Pass the event along with the x value (stored in "data") to
// companySelected
companySelected(e, currentTarget.data);

Barna Biro
01-02-2010, 11:19 PM
From AS 2.0 to Flex? Brave... but also quite blind ( in my opinion ). Don't get me wrong now, but if you really want to get the hang of this, you should first at least read up on some AS 3.0 basics because you'll be more than lost ( as already seen ) with Flex. Just my 2 cents...