Pass object as parameter to onclick method in handlebars template

Ana*_*man 5 javascript json handlebars.js

I have a JSON that looks like this:

{
list: [
        { name: 'AAA',
          id: 1,
          age: 34
        },
        { name: 'BBB',
          id: 2,
          age: 24
        }
      ]
}
Run Code Online (Sandbox Code Playgroud)

And a template like this:

<ul>
    {{#each list}}
        <li onclick="someFunc({{this}})">{{name}} ({{age}}) </li>
    {{/each}}
</ul>
Run Code Online (Sandbox Code Playgroud)

Basically I just want to pass the current object , to a function that does something with it.

Now if I try it, then the generated HTML just has

 ... onclick="someFunc( [object Object] )" ...
Run Code Online (Sandbox Code Playgroud)

whereas I'd like it to be like this:

 ... onclick="someFunc( {name: 'AAA', id: 1, age: 34} )" ...
Run Code Online (Sandbox Code Playgroud)

How can I fix this?

Ana*_*man 5

发布以供将来参考:

从这里得到我的答案:

Handlebars.js 解析对象而不是 [Object object]

原来 Handlebar 在粘贴到模板之前对数据做了一个 toString 。我所要做的就是注册一个将其转换回 json 的辅助方法。

Handlebars.registerHelper('json', function(context) {
    return JSON.stringify(context);
});

<li onclick="someFunc({{json this}})">{{name}} ({{age}}) </li>
Run Code Online (Sandbox Code Playgroud)