Reputation: 1110
I'm using Underscore.js to create a template. I want to make each button in the template pass in the response associated with it. I could do this using the response id, with:
<% _.each(responses, function(response){ %>
<button class="btn btn-sm" onclick="citeResponse('<%= response._id %>')">Cite Response</button>
<% }); %>
and then use
$.grep(responses, function(e){ return e._id == id; });
To find the response based on the id. However, this makes me iterate over an array when I actually know exactly what response I want. I tried doing:
<% _.each(responses, function(response){ %>
<button class="btn btn-sm" onclick="citeResponse('<%= response %>')">Cite Response</button>
<% }); %>
However, citeResponse
always gets [Object object]
. How can I return the actual object?
Upvotes: 0
Views: 954
Reputation: 21
If what you want to pass through the argument is a JSON Object, you can just use JSON.stringify(response)
to serialize it to string. Then, in your citeResponse
function parse it to convert it back to an object with JSON.parse(argument)
.
<% _.each(responses, function(response){ %>
<button class="btn btn-sm" onclick="citeResponse('<%= JSON.stringify(response) %>')">Cite Response</button>
function citeResponse(response) {
response = JSON.parse(response);
...
}
Upvotes: 0