I'm building a simple webapp with just Handlebars.js and some jQuery.
Now I have a list of data, and i present them through a Handlebars-template. Then I want some actions associated with these, e.g. update one element, or delete one. I have buttons that one associates with these actions, the problem is that I cannot manage to get onclick
-methods associated with buttons in the template to work.
I read this question and answer, which lead me to adding the extra bracket and helpermethod, but it still doesn't work. See code below.
Handlebars.registerHelper('json', function(context) {
return JSON.stringify(context);
});
var myGreatFunction = function(someValue) {
// Work with that value
}
The template:
{{#each Something}}
<button onclick="myGreatFunction({{{json this}}})"></button>
{{/each}}
Now, doing it like this give me Uncaught SyntaxError: missing ) after argument list
at the top of the HTML-file.
I noted the answer here, so I tried with onclick="myGreatFunction( '{{{json this}}}' )"
which gives me the error Uncaught SyntaxError: Unexpected token ILLEGAL
at the end of HTML-file.
With onclick="myGreatFunction( '{{json this}}' )"
the button simply disappears on click.
Does anyone see something I've missed, or is there another way of doing this? I thought of adding the object to some div/button in the template, then add a jQuery-listener for the click that fetches the value from the template, but that seems so ugly and unclear.
Any tips? All help is greatly appreciated - thanks in advance.
UPDATE: Seems the problem is, as Hacketo mentioned below, that the outputted JSON is kind of messed up. I inspected an element in my code:
onclick="someFunc('{"id":5,"publisher":null,"message":" asdadsad","address":"asdad","published":"
Last Saturday at 12:00 AM","createdAt":"2015-07
23T09:55:35.486Z","updatedAt":"2015-07-23T09:55:35.486Z"}')"
(Broken over multiple lines for your convenience).
Now I just have to find out of to get that JSON to look right.