Search code examples
javascripthandlebars.js

Send array to function in handlebars?


I have the following piece of code...

 var mainArray = 
{
    nestedArrays:
    {
        array1:[... items ...],
        array2:[... items ...]
    }
};

var source =
    '{{#nestedArrays}}' +
        '{{#each this}}' +
            '<div class="listItem" onclick="populateSecondMenu({{SEND THIS ARRAY!}});">' +
                '<div class="leftSide">' +
                    '<div class="listTitle">Indicator : {{this.length}} </div>' + 
                '</div>' +
            '</div>' +
        '{{/each}}' +          
        '{{/items}}';

var template = Handlebars.compile(source);

$('.list').html(template(mainArray));

As you can already see here, I am able to iterate over this structure, and place the length of both "array1" and "array2" inside list items on the UI.

However, What I also want to be able to do - is to be able to pass the current item to a the function when inside the "#each" tags - see that function call, "populateSecondMenu"? I want to put the array I am at now - so that I can pass that in, How might I do that?

Thanks in advance!


Solution

  • try this. I have used arguments

    <script type="text/javascript">
    function populateSecondMenu(item) {
    
    console.log(arguments);
    }
    </script>
    
    <div class="entry">
      <h1></h1>
      <div class="body">
         {{#nestedArrays}}
            {{#each this}}
                <div class="listItem" onclick="populateSecondMenu({{this}})">
                    <div class="leftSide">
                        <div class="listTitle">Indicator : {{this.length}} </div> 
                   </div>
                </div>
            {{/each}}         
            {{/nestedArrays}}
      </div>
    </div>