Error joining AS2 with AS3 - actionscript-3

I have problems joining two scripts into one.
This is main part of the script: AS3.
And this is already joined script.
And here is part of the code that I need to import (AS2) :
stop();
var banners:Array = new Array();
var imagePaths:Array = new Array();
var links:Array = new Array();
var bodyTexts:Array = new Array();
var imageTime:Number;
var numberOfBanners:Number;
var isRandom:String;
var showHeader:String;
var bannersXML:XML = new XML();
bannersXML.ignoreWhite = true;
bannersXML.load("banners.xml");
bannersXML.onLoad = function(success) {
if (success) {
trace("XML LOADED");
imageTime = parseInt(this.firstChild.firstChild.firstChild)*1000;
numberOfBanners = parseInt(this.firstChild.childNodes[1].firstChild);
isRandom = this.firstChild.attributes["isRandom"];
showHeader = this.firstChild.childNodes[2].attributes["showHeader"];
var bannerSequence:Array = new Array();
if (isRandom == "true") {
//Make a random sequence
while (bannerSequence.length<numberOfBanners) {
newRandomNumber = random(numberOfBanners);
//Make sure that the random one chosen is not already chosen
for (var i = 0; i<=bannerSequence.length; i++) {
if (newRandomNumber != bannerSequence[i]) {
alreadyThere = false;
} else {
alreadyThere = true;
break;
}
}
//Add only random values that aren't in the array
if (!alreadyThere) {
bannerSequence.push(newRandomNumber);
}
}
} else {
for (var i = 0; i<numberOfBanners; i++) {
bannerSequence.push(i);
}
}
}
//Read XML in the Random Order Chosen
for (var i = 0; i<numberOfBanners; i++) {
banners.push(this.firstChild.childNodes[2].childNodes[bannerSequence[i]].firstChild.firstChild.toString());
bodyTexts.push(this.firstChild.childNodes[2].childNodes[bannerSequence[i]].childNodes[1].firstChild.nodeValue);
imagePaths.push(this.firstChild.childNodes[2].childNodes[bannerSequence[i]].childNodes[2].firstChild.nodeValue);
links.push(this.firstChild.childNodes[2].childNodes[bannerSequence[i]].childNodes[3].firstChild.nodeValue);
}
play();
};
//Start the image counter at 0
var imageCounter = 0;
I get erorr in this part of the code
function doRandArray(a:Array):Array {//make random array
var nLen:Number = a.length;
var aRand:Array = a.slice();
var nRand:Number;
var oTemp:Object;
for (var i:Number = 0; i < nLen; i++) {
oTemp = aRand[i];
nRand = i + (random(nLen – i));
aRand[i] = aRand[nRand];
aRand[nRand] = oTemp;
}
return aRand;
}
When I run it, I get an error in this place:
nRand = i + (random(nLen – i));
Scene 1, Layer 'Layer 1', Frame 1, Line 265 1084: Syntax error: expecting rightparen before i.

as2 random(random(nLen – i)); is generate 0,1,...nLen-i-1. not floating only int value.
correct as3 code is int(Math.random()*(nLen-i)); or Math.floor(Math.random()*(nLen-i));
as2: random()
as3: Math.random()

In ActionScript 3 the random function is a little bit different from what it was in as2 code, just change the offending line to:
nRand = i + Math.random()*(nLen-1);
This should fix all errors and work just the same.
EDIT: as #bitmapdata.com indicated, for this to run the same as in as2 the random value must be truncated (stripped of its decimal values). Besides the couple of possibilities he suggested, I would personally just change nRand's type to uint on declaration:
var nRand:uint;
You can also change the iterator type to var i:uint. Less memory usage is always good ;)

Related

Actionscript: How can I create a counter that registers a hitTestObject and shows the score on the main stage?

My game counts the number of hits to an object and brings the user either to a winning or losing page. How can my hitTestObject count the number of hits while showing the number on the main stage? If the user hits "friend" 5 times, I want it to play the "youWin" layer and if they hit a "biter" once, I want it to play the "youLose" layer. (Please help this is for my final project and I'm almost done) Thank you! :)
stop();
addEventListener(Event.ENTER_FRAME,fishHit);
function fishHit(e:Event){
if (theFish.hitTestObject(biter)){
removeEventListener(Event.ENTER_FRAME,fishHit);
gotoAndPlay("youLose");
}
}
var theFish:fish = new fish();
theFish.x = 200
theFish.y = 260
addChild(theFish);
for (var which=0; which<5; which++){
var biter:shark=new shark();
biter.x=1400;
biter.y=int(Math.random()*660.0+30.0);
addChild(biter);
}
for (var what=0; what<5; what++){
var friend:starfish=new starfish();
friend.x=1400;
friend.y=int(Math.random()*660.0+30.0);
addChild(friend);
}
var counter : int = 0;
addEventListener(Event.ENTER_FRAME,winner);
function winner (e:Event){
if(theFish.hitTestObject(friend)) {
counter += 1
scoreboard.score_text.text = counter;
if(counter == 5)
removeEventListener(Event.ENTER_FRAME,winner);
gotoAndPlay("youWin");
}
}
You need many updates in your code, but I'll try to copy and paste your code with small modifications. You should define your variables outside of for loop, also you must add multiple objects like 'friends' to an array.
stop();
// arrays
var friends:Array = new Array();
var biters:Array = new Array();
var counter : int = 0;
var theFish:fish = new fish();
theFish.x = 200
theFish.y = 260
addChild(theFish);
for (var which=0; which<5; which++){
var biter = new shark();
biter.x=1400;
biter.y=int(Math.random()*660.0+30.0);
addChild(biter);
// push it to the array
biters.push(biter)
}
for (var what=0; what<5; what++){
var friend = new starfish();
friend.x=1400;
friend.y=int(Math.random()*660.0+30.0);
addChild(friend);
// push it to the array
friends.push(friend)
}
addEventListener(Event.ENTER_FRAME, enterFrame);
function enterFrame(e:Event){
// theFish vs biters
for (var i:int = 0; i < biters.length; i++){
if (theFish.hitTestObject(biters[i])){
removeEventListener(Event.ENTER_FRAME, enterFrame);
gotoAndPlay("youLose");
}
}
// theFish and friends
for (i = 0; i < friends.length; i++){
if(theFish.hitTestObject(friends[i])) {
// remove this friend so it does not increase counter
friends.splice(i,1);
counter += 1
scoreboard.score_text.text = counter;
if(counter == 5){
removeEventListener(Event.ENTER_FRAME, enterFrame);
gotoAndPlay("youWin");
}
}
}
}

#2007: Parameter format must be non-null?

i have a problem with my as3 code,
i try to link a movie clip to different scene (quiz scene).
so,i have 2 quiz in total, first quiz is using external script (as)
And the second quiz have the same script like first quiz, but i placed the action script inside fla. and it had different xml.
but then this error message appeared:
TypeError: Error #2007: Parameter format must be non-null.
at flash.text::TextField/set defaultTextFormat()
at hiragana/createText()[E:\flash\!!!! FLASH JADI\PAK ASHAR FIX\hiragana.as:80]
at hiragana/kuisdua()[hiragana::frame209:48]
at hiragana/frame209()[hiragana::frame209:249]
this is the code:
// creates a text field
public function createText(text:String, tf:TextFormat, s:Sprite, x,y: Number, width:Number): TextField {
var tField:TextField = new TextField();
tField.x = x;
tField.y = y;
tField.width = width;
tField.defaultTextFormat = tf; //looks like this is the source of problem (-.-)
tField.selectable = false;
tField.multiline = true;
tField.wordWrap = true;
if (tf.align == "left") {
tField.autoSize = TextFieldAutoSize.LEFT;
} else {
tField.autoSize = TextFieldAutoSize.CENTER;
}
tField.text = text;
s.addChild(tField);
return tField;
}
and this is the ettire code
import flash.display.*;
import flash.text.*;
import flash.events.*;
import flash.net.URLLoader;
import flash.net.URLRequest;
///*public class*/ kuisduaa extends MovieClip {
// question data
/*private*/ var dataXML2:XML;
// text formats
/*private*/ var questionFormat2:TextFormat;
/*private*/ var answerFormat2:TextFormat;
/*private*/ var scoreFormat2:TextFormat;
// text fields
/*private*/ var messageField2:TextField;
/*private*/ var questionField2:TextField;
/*private*/ var scoreField2:TextField;
// sprites and objects
/*private*/ var gameSprite2:Sprite;
/*private*/ var questionSprite2:Sprite;
/*private*/ var answerSprites2:Sprite;
/*private*/ var gameButton2:GameButton;
// game state variables
/*private*/ var questionNum2:int;
/*private*/ var correctAnswer2:String;
/*private*/ var numQuestionsAsked2:int;
/*private*/ var numCorrect2:int;
/*private*/ var answers2:Array;
/*public*/ function kuisdua() {
// create game sprite
gameSprite2 = new Sprite();
addChild(gameSprite2);
// set text formats
questionFormat2 = new TextFormat("Arial",80,0xffffff,true,false,false,null,null,"center");
answerFormat2 = new TextFormat("Arial",50,0xffffff,true,false,false,null,null,"left");
scoreFormat2 = new TextFormat("Arial",30,0xffffff,true,false,false,null,null,"center");
// create score field and starting message text
scoreField2 = createText("",scoreFormat,gameSprite,-30,550,550);
messageField2 = createText("Loading Questions...",questionFormat,gameSprite,0,50,550);
// set up game state and load questions
questionNum2 = 0;
numQuestionsAsked2 = 0;
numCorrect2 = 0;
showGameScore2();
xmlImport2();
}
// start loading of questions
/*public*/ function xmlImport2() {
var xmlURL:URLRequest = new URLRequest("kuis2.xml");
var xmlLoader:URLLoader = new URLLoader(xmlURL);
xmlLoader.addEventListener(Event.COMPLETE, xmlLoaded);
}
// questions loaded
/*public*/ function xmlLoaded2(event:Event) {
dataXML = XML(event.target.data);
gameSprite.removeChild(messageField);
messageField = createText("Tap Untuk Memulai",scoreFormat,gameSprite,-10,250,500);
showGameButton("mulai");
}
// creates a text field
/*public*/ function createText2(text:String, tf:TextFormat, s:Sprite, x,y: Number, width:Number): TextField {
var tField2:TextField = new TextField();
tField2.x = x;
tField2.y = y;
tField2.width = width;
tField2.defaultTextFormat = tf;
tField2.selectable = false;
tField2.multiline = true;
tField2.wordWrap = true;
if (tf.align == "left") {
tField2.autoSize = TextFieldAutoSize.LEFT;
} else {
tField2.autoSize = TextFieldAutoSize.CENTER;
}
tField2.text = text;
s.addChild(tField2);
return tField2;
}
// updates the score
/*public*/ function showGameScore2() {
scoreField2.text = "Soal: "+numQuestionsAsked2+" Benar: "+numCorrect2;
}
// ask player if they are ready for next question
/*public*/ function showGameButton2(buttonLabel:String) {
gameButton = new GameButton();
gameButton.label.text = buttonLabel;
gameButton.x = 240;
gameButton.y = 480;
gameSprite2.addChild(gameButton);
gameButton.addEventListener(MouseEvent.CLICK,pressedGameButton2);
}
// player is ready
/*public*/ function pressedGameButton2(event:MouseEvent) {
// clean up question
if (questionSprite2 != null) {
gameSprite2.removeChild(questionSprite2);
}
// remove button and message
gameSprite2.removeChild(gameButton);
gameSprite2.removeChild(messageField2);
// ask the next question
if (questionNum >= dataXML.child("*").length()) {
gotoAndStop(6);
} else {
askQuestion2();
}
}
// set up the question
/*public*/ function askQuestion2() {
// prepare new question sprite
questionSprite2 = new Sprite();
gameSprite2.addChild(questionSprite2);
// create text field for question
var question2:String = dataXML.item[questionNum].question2;
if (dataXML.item[questionNum].question.#type == "text") {
questionField2 = createText(question2,questionFormat2,questionSprite2,50,150,300);
} else {
var questionLoader2:Loader = new Loader();
var questionRequest2:URLRequest = new URLRequest("triviaimages/"+question2);
questionLoader2.load(questionRequest2);
questionLoader2.y = 150;
questionLoader2.x = 180;
questionSprite2.addChild(questionLoader2);
}
// create sprite for answers, get correct answer and shuffle all
correctAnswer2 = dataXML.item[questionNum2].answers.answer[0];
answers2 = shuffleAnswers(dataXML.item[questionNum2].answers);
// put each answer into a new sprite with a icon
answerSprites2 = new Sprite();
var xpos:int = 0;
var ypos:int = 0;
for(var i:int=0;i<answers2.length;i++) {
var answerSprite2:Sprite = new Sprite();
if (answers2[i].type == "text") {
var answerField2:TextField = createText(answers2[i].value,answerFormat2,answerSprite2,30,-35,200);
} else {
var answerLoader2:Loader = new Loader();
var answerRequest2:URLRequest = new URLRequest("triviaimages/"+answers2[i].value);
answerLoader2.load(answerRequest2);
answerLoader2.y = -22;
answerLoader2.x = 25;
answerSprite2.addChild(answerLoader2);
}
var letter:String = String.fromCharCode(65+i); // A-D
var circle:Circle = new Circle(); // from Library
circle.letter.text = letter;
circle.answer = answers[i].value;
answerSprite2.x = 100+xpos*250;
answerSprite2.y = 350+ypos*100;
xpos++
if (xpos > 1) {
xpos = 0;
ypos += 1;
}
answerSprite2.addChild(circle);
answerSprite2.addEventListener(MouseEvent.CLICK,clickAnswer); // make it a button
// set a larger click area
answerSprite2.graphics.beginFill(0x000000,0);
answerSprite2.graphics.drawRect(-50, 0, 200, 80);
answerSprites2.addChild(answerSprite2);
}
questionSprite2.addChild(answerSprites2);
}
// take all the answers and shuffle them into an array
/*public*/ function shuffleAnswers2(answers:XMLList) {
var shuffledAnswers2:Array = new Array();
while (answers2.child("*").length() > 0) {
var r:int = Math.floor(Math.random()*answers.child("*").length());
shuffledAnswers2.push({type: answers2.answer[r].#type, value: answers2.answer[r]});
delete answers2.answer[r];
}
return shuffledAnswers2;
}
// player selects an answer
/*public*/ function clickAnswer2(event:MouseEvent) {
// get selected answer text, and compare
var selectedAnswer2 = event.currentTarget.getChildAt(1).answer;
if (selectedAnswer2 == correctAnswer2) {
numCorrect++;
messageField2 = createText("Hai, kamu benar ! ",scoreFormat2,gameSprite2,-30,280,550);
} else {
messageField2 = createText("Iie, Jawabanmu Salah, yang benar adalah:",scoreFormat2,gameSprite2,53,280,370);
}
finishQuestion();
}
/*public*/ function finishQuestion2() {
// remove all but the correct answer
for(var i:int=0;i<4;i++) {
answerSprites2.getChildAt(i).removeEventListener(MouseEvent.CLICK,clickAnswer);
if (answers2[i].value != correctAnswer2) {
answerSprites2.getChildAt(i).visible = false;
} else {
answerSprites2.getChildAt(i).x = 200;
answerSprites2.getChildAt(i).y = 400;
}
}
// next question
questionNum2++;
numQuestionsAsked2++;
showGameScore2();
showGameButton2("Lanjutkan");
}
// clean up sprites
/*public*/ function CleanUp2() {
removeChild(gameSprite);
gameSprite2 = null;
questionSprite2 = null;
answerSprites2 = null;
dataXML2 = null;
}
the first quiz played perfectly with that code,
and i have no clue why this error appeared,
i'm beginner in as3 so i'm still lack in many ways,
can anyone help me,?
i really apreciate it.. :)
Are you sure that you're parsing a non-null TextFormat instance as the second argument of createText()?
The error means that you're supplying a null value for tf:TextFormat.
Unless I am missing something, your issue is here:
messageField2 = createText("Loading Questions...",questionFormat,gameSprite,0,50,550);
&
messageField = createText("Tap Untuk Memulai",scoreFormat,gameSprite,-10,250,500);
I see questionFormat2 and scoreFormat2 are instantiated, but I never see a questionFormat or scoreFormat. Your error says that the defaultTextFormat (or TextFormat supplied using setTextFormat(), for future reference), cannot be null. Null means that the object has not been instantiated/created yet. questionFormat and scoreFormat are never instantiated. Hell, their variables do not even exist. If you were using a proper development IDE (FlashBuilder, FlashDevelop, etc), you'd never be able to compile this code.
Switch those two lines to use the correct formats and you should be fine.

AS3: Casting to Vector

I am trying to create a vector from unknown class, but it fails, any ideas about how to do it?
This is what i tried:
var vector:Vector = new Vector(); // throw exception
function base():void{
var vector:Vector.<String> = createVector(String);// throw classCastException
}
function createVector(cls:Class):*{
var array:Array = new Array();
for(var i:int = 0; i < 10; i++){
var element:cls = new cls();
array.push(element);
}
return Vector(array);
}
Vector is expecting a parameter type so you can't do this like you want, but using getQualifiedClassName to get class info you can construct a string that will enable you to call the Vector. constructor using getDefinitionByName :
Ex.
// get class parameter name
var className:String=getQualifiedClassName(String);
// get the Vector class object for the given class
var o:Object=getDefinitionByName("__AS3__.vec::Vector<"+className+">");
// call the constructor
var v:*=o.prototype.constructor(["hello", "world"]);
So your function can be written as:
public function createVector(cls:Class):*{
var cn:String = getQualifiedClassName(cls);
var o:Object = getDefinitionByName("__AS3__.vec::Vector.<"+cn+">");
var array:Array = [];
for(var i:int = 0; i < 10; i++){
var element:* = new cls();
array.push(element);
}
return o.prototype.constructor(array);
}
live example at wonderfl:
http://wonderfl.net/c/pkjs
Based on #Patrick answer I found a working solution.
Check it out:
function createVector(cls:Class):*{
var className:String = getQualifiedClassName(cls);
var vectorClass:Class = getDefinitionByName("__AS3__.vec::Vector.<"+className+">") as Class;
var vector:* = new vectorClass(10);
for(var i:int = 0; i < 10; i++){
var element:MyClass = new cls(); // may be Object or Object extends cls
vector[i] = element;
}
return vector;
}

AS3 Closure Confusion

I have a small loop
var a:Array = [{name:Test1},{name:Test2},{name:Test3},{name:Test4}]
var b:GenericButton; //A pretty basic button component
for(var i:int = 0; i < a.length; i++){
b = new GenericButton(a[i].name, function():void { trace(i) });
this.addChild(b);
}
The function supplied to the GenericButton is executed when the button is pressed.
The problem I am having is that when the no matter what button I press the value of 4 (the length of the array) is always output.
How would I ensure that I trace 0 when the first button is pushed, 1 when the second is pushed, etc?
Well, you can simply do:
var f:* = function():void { trace(arguments.callee.index) };
f.index = i;
b = new GenericButton(a[i].name, f);
Better still:
function createDelegate(obj:Object, func:Function):Function
{
var f:* = function ():* {
var thisArg:* = arguments.callee.thisArg;
var func:* = arguments.callee.func;
return func.apply(thisArg, arguments);
};
f.thisArg = obj;
f.func = func;
return f;
}
...
for (...) {
b = new GenericButton(a[i].name,
createDelegate({index: i}, function():void { trace(this.index) }));
}
And in some (most?) cases it would be even better if you created a separate class and passed i into the constructor.
This is most basic error when using closures. You might be thinking that i is set when GenericButton is created. But closure just get direct link to variable i and uses this link when anonymous function is called. By this time, cycle is finished, and all links to i are pointing to same integer with value = 4.
To fix this, just pass value of i somehow - for example, as an additional argument to GenericButton constructor. In this case, a copy of i will be created on each step, with values of 0, 1, 2, 3 - just like you need.
...
b = new GenericButton(a[i].name, function(i:int):void { trace(i); }, i);
...
Store i in GenericButton and pass into function - this causes anonymous function to stop using context variable i (cycle counter) and forces it to use argument i.
Make a function that returns a function. Here's a FlexUnit test method that demonstrates it.
[Test]
public function closureWin():void
{
var functions:Array = [];
var mkFn:Function = function(value:int):Function
{
return function():int
{
return value;
}
}
var i:int;
for (i = 0; i < 10; i++)
{
functions.push(mkFn(i));
}
var j:int;
for(j = 0; j < 10; j++)
{
assertEquals(j, functions[j]());
}
}
Here's a test method demonstrating the behavior you are seeing:
[Test]
public function closureFail():void
{
// basically to see if this works the same way in as3 as it does in javascript
// I expect that all the functions will return 10
var i:int;
var functions:Array = [];
for (i = 0; i < 10; i++)
{
functions.push(function():int{return i});
}
var j:int;
for each (var f:Function in functions)
{
assertEquals(10, f());
}
}

Closure problem? - passing current value of a variable

I'm trying to pass the current value of a variable when an a dynamically generated navigation 'node' is clicked. This needs to just be an integer, but it always results in the last node's value.. have tried some different methods to pass the value, a custom event listener, a setter, but I suspect it's a closure problem.. help would be appreciated ;-)
function callGrid():void {
for (var i:Number = 0; i < my_total; i++) {
var gridnode_url = my_grid[i].#gridnode;
var news_category= my_grid[i].#category;
var newstitle = my_grid[i].#newstitle;
var news_content = my_grid[i]..news_content;
var news_image = my_grid[i]..news_image;
var gridnode_loader = new Loader();
container_mc.addChild(gridnode_loader);
container_mc.mouseChildren = false;
gridnode_loader.load(new URLRequest(gridnode_url));
gridnode_loader.contentLoaderInfo.addEventListener(Event.COMPLETE, gridLoaded);
gridnode_loader.name = i;
text_container_mc = new MovieClip();
text_container_mc.x = 0;
text_container_mc.mouseEnabled = false;
var textY = text_container_mc.y = (my_gridnode_height+18)*y_counter;
addChild(text_container_mc);
var tf:TextSplash=new TextSplash(newstitle,10,0,4 );
container_mc.addChild(tf);
tf.mouseEnabled = false;
tf.height = my_gridnode_height;
text_container_mc.addChild(tf);
var text_container_mc_tween = new Tween(text_container_mc, "alpha", Strong.easeIn, 0,1,0.1, true);
gridnode_loader.x = (my_gridnode_width+5) * x_counter;
gridnode_loader.y = (my_gridnode_height+15) * y_counter;
if (x_counter+1 < columns) {
x_counter++;
} else {
x_counter = 0;
y_counter++;
}
}
}
function gridLoaded(e:Event):void {
var i:uint;
var my_gridnode:Loader = Loader(e.target.loader);
container_mc.addChild(my_gridnode);
_xmlnewstarget = my_gridnode.name;
//||||||||||||||||||||||||||||||||||||||||
//when a particular grid node is clicked I need to send the current _xmlnewstarget value to the LoadNewsContent function...
//||||||||||||| ||||||||||||||||||||||||
my_tweens[Number(my_gridnode.name)]=new Tween(my_gridnode, "alpha", Strong.easeIn, 0,1,0.1, true);
my_gridnode.contentLoaderInfo.removeEventListener(Event.COMPLETE, gridLoaded);
my_gridnode.addEventListener(MouseEvent.CLICK, loadNewsContent);
}
function loadNewsContent(e:MouseEvent):void {
createNewsContainer();
getXMLNewsTarget();
news_category = my_grid[_xmlnewstarget].#category;
var tfnews_category:TextSplash=new TextSplash(news_category,20,16,32,false,false,0xffffff );
tfnews_category.mouseEnabled = false;
newstitle = my_grid[_xmlnewstarget].#newstitle;
var tftitle:TextSplash=new TextSplash(newstitle,20,70,24,false,false,0x333333 );
news_container_mc.addChild(tftitle);
tftitle.mouseEnabled = false;
news_content = my_grid[_xmlnewstarget]..news_content;
var tfnews_content:TextSplash=new TextSplash(news_content,20,110,20,true,true,0x333333,330);
news_container_mc.addChild(tfnews_content);
tfnews_content.mouseEnabled = false;
news_image = my_grid[_xmlnewstarget].#news_image;
loadNewsImage();
addChild(tfnews_category);
addChild(tftitle);
addChild(tfnews_content);
var news_container_mc_tween = new Tween(news_container_mc, "alpha", Strong.easeIn, 0,1,0.3, true);
news_container_mc_tween.addEventListener(Event.INIT, newsContentLoaded);
}
I'm not going to try to read your code (try to work on your formatting, even if it's just indenting), but I'll provide a simplified example:
for (var i = 0; i < my_total; i++) {
var closure = function() {
// use i here
}
}
As you say, when closure is called it will contain the last value of i (which in this case would be my_total). Do this instead:
for (var i = 0; i < my_total; i++) {
(function(i) {
var closure = function() {
// use i here
}
})(i);
}
This creates another function inside the loop which "captures" the current value of i so that your closure can refer to that value.
See also How does the (function() {})() construct work and why do people use it? for further similar examples.
Umm, as mentioned above, the code is a bit dense, but I think you might have a bit of type conversion problem between string and integers, is the "last value" always 0? try making these changes and let me know how you get on.
// replace this gridnode_loader.name = i;
gridnode_loader.name = i.toString();
// explictly type this as an int
_xmlnewstarget = parseInt(my_gridnode.name);
// replace this: my_tweens[Number(my_gridnode.name)] = new Tween(......
my_tweens[parseInt(my_gridnode.name)] = new Tween();
Oh and I think it goes without saying that you should massively refactor this code block once you've got it working.
Edit: after further study I think you need this
//replace this: my_gridnode.addEventListener(MouseEvent.CLICK, loadNewsContent);
var anonHandler:Function = function(e:MouseEvent):void
{
loadNewsContent(_xmlnewstarget);
};
my_gridnode.addEventListener(MouseEvent.CLICK, anonHandler);
Where your loadNewsContent has changed arguements from (e:MouseEvent) to (id:String)
Firstly, you do not need to call addChild for the same loader twice (once in callGrid) and then in (gridLoaded). Then you can try putting inside loadNewsContent: news_category = my_grid[int(e.target.name)].#category;instead of news_category = my_grid[_xmlnewstarget].#category; As _xmlnewstarget seems to be bigger scope, which is why it is getting updated every time a load operation completes.