actionscript 2 - How can I simplify this small code with a loop in AS2 -


the following code want simplify:

    _root.botao1.onrelease = function(){         follow=1;     }     _root.botao2.onrelease = function(){         follow=2;     }     _root.botao3.onrelease = function(){         follow=3;     } 

i have tried implement following code:

for(i=0;i<3;i++){     _root['botao'+i].onrelease = function(){         follow=i;         trace(follow);     } } 

although should work, when trace current follow value return in '3', no meter if click on 1 or 2.

how can fixed?

the reason buttons print same value because onrelease functions reference same variable i, contains value 3 when loop has finished executing.

an easy solution store value of each iteration of loop variable on clickable object:

for(i = 0; < 3; i++) {    var mc : movieclip = _root['botao' + i];    mc.follow = + 1;    mc.onrelease = function(){       trace(this.follow);    } } 

another solution might bit harder grasp define anonymous function , call (notice () @ end). anonymous function stores current value of inside own scope in variable called follow, returns anonymous function (contaning logic want run when onrelease triggered). function returned has access follow variable:

for(i = 0; < 3; i++) {     _root['botao' + i].onrelease = (function() {         var follow = + 1;         return function(){             trace(follow);         }     })(); }  

Comments

Popular posts from this blog

linux - xterm copying to CLIPBOARD using copy-selection causes automatic updating of CLIPBOARD upon mouse selection -

c++ - qgraphicsview horizontal scrolling always has a vertical delta -