Search code examples
jquery-templatesjquery

How to convert a string to jquery object?


I am using jquery template for my project. The problem I am facing is that when rendering a template I am converting $data to string and passing it in onclick function [see the code below].

<script id="Item" type="text/x-jquery-tmpl">
    <li id="${ID}" class="card red ui-state-default">
        <a class="desc" href="" onclick="return $$.popup.eItem('${($data)}');"> ${$data.Desc} </a> 
    </li>
</script>

the converting of $data object to string and passing it to a function

onclick="return $$.popup.eItem('${($data)}');"

here, $data is an object containing the actual data. And when I click the link I get the passed string as "[object Object]" and I want to convert it again back to jquery object so I can use it in my code.

I can use 'JSON.stringify()' to convert the $data object to JSON, like this

onclick="return $$.popup.editCard('${JSON.stringify($data)}');"

but as the template is rendered to html, this is the output:

<a class="desc" href="" onclick="return $$.popup.eItem('{&quot;TemplateName&quot;:&quot;CardItem&quot;,&quot;ID&quot;:&quot;lc822&quot;,&quot;Desc&quot;:&quot;make card EntityAssignId = 0&quot;,&quot;CardId&quot;:822,&quot;LaneId&quot;:665,&quot;Priority&quot;:1,&quot;AssignedEntityId&quot;:0,&quot;Pic&quot;:null,&quot;SortOrder&quot;:2}');">make card EntityAssignId = 0</a>

So any suggestion?


Solution

  • Well if you want to access the properties of the data object maybe you should access them:

     onclick="return $$.popup.eItem('${($data.ID)}');"
    

    In this way you will get the ID property. You get "[object Object]" because that's the way that javascript uses to convert an object tio a string (you would get the same if you called alert($data);

    From your expample I would expect my code to be converted to

    <a class="desc" href="" onclick="return $$.popup.eItem('lc822');">make card EntityAssignId = 0</a>
    

    because from your "Stringified" code i can see that the property ID of $data is equal to lc822