Shehryar Farooq
Shehryar Farooq

Reputation: 115

Access to model object by EL in javascript function?

Here is my markup, I am using jtsl core tag

<c:forEach var="attr" items="${attributes}">
    <c:when test='${attr.controlType == "textField"}'>
        <script>createTextField("${attr}");</script>
        </c:when>
</c:forEach>

So the "attributes" is a list of objects which resides in the model.

I want to call the createTextField function and I want access to the "attr" in that function.

Here is my function, but I can't get access to the object, says it is undefined.

function createTextField(object) {
    document.write(object.name);        
}

Any ideas? would be appreciated.

Upvotes: 1

Views: 2728

Answers (1)

BalusC
BalusC

Reputation: 1108692

This is not going to work. Java and JavaScript doesn't run in the same environment. You're basically passing attr.toString() to the JavaScript function which look by default like com.example.ClassName@hashcode. The JavaScript String object doesn't have a name property.

There are basically two ways to get it to work:

  1. You need to convert the Java object as represented by #{attr} to a string which conforms the JavaScript object notation (also known as JSON). E.g.

    <script>createTextField(${attr.asJson});</script>
    

    with something like (with little help of Gson):

    public String getAsJson() {
        return new Gson().toJson(this);
    }
    

    You can of course also manually build it using StringBuilder or something. JSON format isn't that hard.

  2. Pass only the property/properties of interest as long as they can be represented as String. E.g.

    <script>createTextField("${attr.name}");</script>
    

    with

    function createTextField(name) {
        document.write(name);        
    }
    

Upvotes: 4

Related Questions