Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

how to dynamically assign unique id's to buttons 1

Status
Not open for further replies.

BluesmanUK

Programmer
Dec 17, 2001
55
GB
Hi there, I wonder if anyone can answer a question thats been bugging me for a while. All i want to do is create a bunch of buttons, each passing a unique id to a function when clicked. Something like this:

function createButtons() {

for (var i=0; i<buttonArray.length; i++) {
_root.attachMovie("button_mc", "button"+i, i);

// some code to position the buttons
_root["button"+i]._x = 0;
_root["button"+i]._y = (_root["button"+i]._height)*i;


_root["button"+i].onRelease = function() {
// here is where i get a bit confused
trace("button " + i + " was clicked");
}
// this doesnt work either
// _root["button"+i].onRelease = doClick(i);

}

}

im sure theres a really easy answer, Im probably not following best practice for actionscript coding , so any advice would be most welcome!
cheers,
James
 
Try something like:
Code:
function createButtons() {
	for (var i = 0; i<buttonArray.length; i++) {
		_root.attachMovie("button_mc", "button"+i, i);
		// some code to position the buttons
		_root["button"+i]._x = 0;
		_root["button"+i]._y = (_root["button"+i]._height)*i;
		[b]_root["button"+i]["id"] = i;[/b]
		_root["button"+i].onRelease = function() {
			//  here is where i get a bit confused
			[b]trace(this._name);[/b]
			trace("button "+[b]this.id[/b]+" was clicked");
		};
	}
}

Kenneth Kawamoto
 
_root["button"+i]["id"] = i;

Think that should be...

_root["button"+i].id = i;
Not really.

In this particular case, these two are interchangeable. But if you do Object.Property instead of Object[Property] to create a property dynamically in a non-dynamic Class definition you'll run into a trouble.

For example, this Class creates a dynamic property with dot operator:
Code:
class Test{
	function Test(){
		this.aProperty = "boo";
		trace(this.aProperty);
	}
}
[tt]
// Output
**Error** Test.as: Line 3: There is no property with the name 'aProperty'.
this.aProperty = "boo";
[/tt]
But with "[]" (Array Access Operator):
Code:
class Test{
	function Test(){
		this["aProperty"] = "boo";
		trace(this["aProperty"]);
	}
}
[tt]
// Output
boo
[/tt]
So they are almost the same but in a way "[]" is more powerful because of the above.

Kenneth Kawamoto
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top