Search code examples
javascriptjqueryhandlebars.js

Onclick-function on elements in Handlebars-template


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('{&quot;id&quot;:5,&quot;publisher&quot;:null,&quot;message&quot;:&quot; asdadsad&quot;,&quot;address&quot;:&quot;asdad&quot;,&quot;published&quot;:&quot
Last Saturday at 12:00 AM&quot;,&quot;createdAt&quot;:&quot;2015-07
23T09:55:35.486Z&quot;,&quot;updatedAt&quot;:&quot;2015-07-23T09:55:35.486Z&quot;}')"

(Broken over multiple lines for your convenience).

Now I just have to find out of to get that JSON to look right.


Solution

  • This is because JSON.stringify return a JSON string and contains ".

    At the moment, your template may look like this:

    <button onclick="myGreatFunction({{{json this}}})"></button>
    

    Compiled :

    <button onclick="myGreatFunction({"foo":"bar"})"></button>
                    ^                 ^   ^ ^   ^  ^
    

    And this result as

    Uncaught SyntaxError: missing ) after argument list


    You need to escape those " and you can do this in your helper

    Handlebars.registerHelper('json', function(context) {
        return JSON.stringify(context).replace(/"/g, '&quot;');
    });
    

    And this will result as

    <button onclick="myGreatFunction({&quot;foo&quot;:&quot;bar&quot;})"></button>