Friday, September 10, 2010

javascript eval() does not have scope to a local variable

I have a JSNI method that I want to pass two strings, one that is the
JSON response from a server, and one that is a JavaScript snippet that
will parse the JSON and return a list of JavaScriptObjects to be
displayed in a combo box (the JavaScriptObjects will contain displays
and values). The reasons for doing this this way is complicated, but I
believe it shouldn't be terribly hard to do. It looks like this
currently:

private native List<ItemJavaScriptObject> parseObjects(String
jsonParser, String jsonText) /*-{
var ref = eval('(' + jsonText + ')');
return eval(jsonParser);
}-*/;

Examples of my strings as they're being passed to the method
(retrieved with a $wnd.alert):

jsonText: [{"display":"Active","value":"active"},
{"display":"Canceled","value":"canceled"}]
jsonParser: newArray = new Array(); for (index = 0; index <
ref.length; ++index) { newArray[index] = {"display":
ref[index].display, "value": ref[index].value}; } newArray;

In development mode it blows up on "return eval(jsonParser)" with:
"com.google.gwt.core.client.JavaScriptException: (ReferenceError): ref
is not defined".

Oddly, if I paste the following into the Chrome console, it runs
successfully and returns the array of objects with the appropriate
values:

var ref = eval( '(' + '[{"display":"Active","value":"active"},
{"display":"Canceled","value":"canceled"}]' + ')' );
jsonParser = "newArray = new Array(); for (index = 0; index <
ref.length; ++index) { newArray[index] = {\"display\":
ref[index].display, \"value\": ref[index].value}; } newArray;";
eval(jsonParser);

--
You received this message because you are subscribed to the Google Groups "Google Web Toolkit" group.
To post to this group, send email to google-web-toolkit@googlegroups.com.
To unsubscribe from this group, send email to google-web-toolkit+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/google-web-toolkit?hl=en.

No comments:

Post a Comment