views:

67

answers:

3

I'm passing a Javascript Array() to Flash via FlashVars but Flash complains. Can you guys point me what am I doing wrong here?

javascript code

// array with the user defined cities
var usercities = new Array( 
    {'nome':"London", 'lat':51.5002, 'long':-0.1262 },
    {'nome':"NYC", 'lat':51.5002, 'long':-0.1262 } 
);

flashvars.newcities = usercities;

flash code

// this array is pre-populated so if the users doesn't enter data this is shown
var cities:Array = new Array(
    { nome:"London", lat:51.5002, long:-0.1262 },
    { nome:"NYC", lat:40.7144, long:-74.0060 }
);

// gets FlashVars
var newcities:Object = LoaderInfo(this.root.loaderInfo).parameters.newcities;
if(newcities != null) {
    cities = newcities;
};

Doesn't work. I need to have the cities array on the Flash Side exactly as it is. On the Javascript side all code can change.

Thank you for your help.

A: 

Well you can just manually make them arrays. Something like this:

var usercities = [];
usercities[0] = [];
usercities[0]["nome"] = "London";
usercities[0]["lat"] = 51.5002
usercities[0]["long"] = -0.1262
usercities[1] = [];
usercities[1]["nome"] = "NYC";
usercities[1]["lat"] = 51.5002
usercities[1]["long"] = -0.1262

Though I think it is all the same but flash may be seeing it differently.

spinon
@spinon actually this turns out to be two empty arrays. Funny. Still trying to do it.
Frankie
That is too bad. So why not use an array of objects?
spinon
@spinon, well... just went the easy way. Changed all the flash code to refer to the items by position [0], [1], [2] and passed the array as a string split by comma's. On Flash exploded that string and converted to an Array. Not pretty but works. Thank you for your help.
Frankie
Yeah I guess that is the easiest way to do it. That is strange that you couldn't get it to work the other way but glad something is working for you.
spinon
A: 

JavaScript does not have associative arrays like other languages. In order to have named indexes, you have to use an object. An array that is assigned a value with a named index will be converted to an object.

In order to do this, you may need to change your Flash code. As meder said, serializing your array is your best bet. I'd suggest a JSON encode in the JavaScript and a decode in the Flash.

Ryan Kinal
@Ryan I'll probably have to serialize it as you say. Been trying to parse it this far with no result whatsoever...
Frankie
A: 

Ended up passing the values as this:

javascript

var cities = new Array( 
    Array("London", 51.5002, -0.1262),
    Array("NYC", 40.7144, -74.0060),
);

That flash gets as a pure string.

"London",51.5002,-0.1262,"NYC",40.7144,-74.0060

I then exploded the string and converted to Array. It's a bit dirty but in the end works. As long as the Array always has 3 items per row and no item has a comma.

Hope this may help someone.

Frankie