Set a global value to {{this}} on click with Handlebars

I’m writing this simple client side app that works with an API. It’s simply jQuery and Handlebars.

I have an array that I fetch from my server, and hands to a Handlebars-template.

<div id="value-selection-container">
    <script id="value-selection-template" type="text/x-handlebars-template">
        {{#each values}}
            <button type='button' class="btn btn-default" aria-label="Left Align" onclick="someGlobalObject.value={{this}}" >{{this}}</button>

Then I fetch data from server, and pass to my template:

getSomeData(function(data){  // Get possible route codes from server
    source = $('#value-selection-template').html(); // Get the HTML source of the template
    template = Handlebars.compile(source); // Compile it
    $('#value-selection-container').html(template({"values" : data}));// Pass data to template

For some reason this does not work, I’m assuming because the template cannot handle JavaScript like that?

I moved on to trying to add a helper, but that does not seem to work either. I change the onclick to onclick="{{setValue this}}", and add a helper before I compile the template:

Handlebars.registerHelper('setValue', function(someNewValue){
    someGlobalObject.value = someNewValue;

Now it sets the value to the last one in the list, no matter which button I click. I added a console.log to the helper, and found that the helper is called for every item in the list while the template is compiled, which then is the reason for the last item always being the selected one. When the template is pushed to HTML, it seems the onclicks have been made ineffective.

What have I missed? How would I go through with this sort of selection with Handlebars? All help is greatly appreciated. Thanks in advance!

Source: javascript

Leave a Reply