How I access a variable from JavaScript and Grails?

I have a Grails variable which is of type JASONList that is rendered in a template.

Is there a way to access this list from inside a JavaScript function?

Let’s say I want onresize to fit all the objects on the screen. Without making a database call and refetching the entire list from Ajax…

Let’s say the template does something like this:

<g:each var="report" in="${reportList?.myArrayList}">
  <li style="display:inline; list-style:none;">
    <img src="  ${report?.img}">
  </li>
</g:each>
<script type="text/javascript">
    function resize(list) {
        if (list.size <givenSize) // Pseudocode
            list.subList() // Pseudocode
    }
    window.onresize = resize("${reportList}")
</script>

The problem with this is that for some reason Grails gsp does not render “${reportList}” as a list. Instead it renders it as the string “${reportList}”.

I am probably thinking of this problem completely wrong, but is there a way to resize these objects or get them through document.getElementById or something of that nature?

The $reportList is populated by POJO as JSON conversion…

Answer

I figured out my problem. Basically if you are using POJO in Grails the Grails as JSON conversion is not very smart. All it does is a toString on the object instead of potentially looking at all the public accessors, etc.

It is kind of disappointing, but basically I need to create the JSON conversion in the toString method of my POJO.

Leave a Reply

Your email address will not be published. Required fields are marked *