Reputation: 159
I need to manage a groovy list object in my javascript function. I have a groovy block into a javascript function. I tried with this:
var obj = ${mediaObjectInstanceList as grails.converters.JSON}[index];
and this:
var obj = ${mediaObjectInstanceList.get(index)};
but both are wrong. In the second I would specify the "index" int javascript variable out of the groovy block.
Upvotes: 1
Views: 1879
Reputation: 893
As answered by injecteer, you can't do that. Mostly because :
mediaObjectInstanceList
(only known by your grails application).Two (main) solutions :
you don't know your index when the page is generated (no params in your request) => You have to generate the whole array server side (groovy) to be available at client side (javascript).
var mediaObjectInstanceListInJS = new Array( ${mediaObjectInstanceList.collect { it as JSON}.join(',')} ); var someVal = mediaObjectInstanceListInJS[index];
you already have the index server side (with params in your request) => you can get in groovy block only your selected object :
var someVal = ${mediaObjectInstanceListInJS[params.index] as JSON} ;
Upvotes: 0
Reputation: 20699
You can't do that in a way you defined it.
Though, there are lots of possibilities to accomplish that.
One of them is to define a JS-variable and fill it with groovy model values:
var myArray = new Array(
<g:each in="${mediaObjectInstanceList}" var="obj" status="ix">
${status ? ',' : ''} '${obj}'
</g:each>
);
then you can traverse this array in JS using plain subscript notation:
var someVal = myArray[ index ];
Upvotes: 1