Skip to main content
Inspiring
June 13, 2006
Question

Dynamically generated functions

  • June 13, 2006
  • 2 replies
  • 339 views
Hi Folks

I have asked a similar question before but it does not quite answer this problem.

I wish to dynamically generate functions based on a number generated from xml - in the example below I use var totalCount to represent such a variable.

var totalCount = 4;
for (var i = 1; i<totalCount+1; i++) {
_root["func"+i] = function () {
trace(i);
};
trace(i) // this traces 1,2,3,4
}

if I then have a button "b1" with the following code . . .

b1.onRelease=function(){
_root.func2()
}
. .what I would like to see is '2' traced in the output panel. However, I get '4'
This topic has been closed for replies.

2 replies

June 13, 2006
yes, That is because i does equal four
because when the user clicks the button, the loop has run 4 times, so its last value is 4.

so basically you need a way to store the i number in the loop so that it can be accessed by the same function with i in its its name.

with out thinking about it too much.. why not pass i in the function's arguments:
var totalCount = 4;
for (var i = 1; i < totalCount + 1; i ++)
{
_root ["func" + i] = function (id:Number)
{
trace (id - 1);
};
}

June 13, 2006
no no no that was stupid and wrong

i'll probably have to think a little bit longer
pwiopAuthor
Inspiring
June 13, 2006
Hey, no problems dude, it was kind of you to take time trying to help - thank you
June 13, 2006
your code is fine, your logic in you tracing is wrong.

after the loop has ended i will aways be 4
trace a unique word in each instead
pwiopAuthor
Inspiring
June 13, 2006
Thank you for your response but actually 'no', it does not work. For example make four button instances on the stage name them b1, b2, b3, b4.

Add the following code to the timeline;

var totalCount = 4;
for (var i = 1; i<totalCount+1; i++) {
_root["func"+i] = function () {
trace(i-1);
};
}
b1.onRelease = function() {
_root.func1();
};
b2.onRelease = function() {
_root.func2();
};
b3.onRelease = function() {
_root.func3();
};
b4.onRelease = function() {
_root.func4();
};

What I want is for b1 to output "1", b2 to output "2" etc. As it is each button outputs "4"