我正在使用Handlebars.js和一些jQuery构建一个简单的webapp。
现在我有一个数据列表,我通过Handlebars模板呈现它们。然后我想要一些与这些相关的行动,例如更新一个元素,或删除一个元素。我有一些与这些操作相关联的按钮,问题是我无法设法获得与模板中的按钮相关联的onclick
方法。
我读了this question and answer,它引导我添加额外的括号和helpermethod,但它仍然不起作用。见下面的代码。
Handlebars.registerHelper('json', function(context) {
return JSON.stringify(context);
});
var myGreatFunction = function(someValue) {
// Work with that value
}
模板:
{{#each Something}}
<button onclick="myGreatFunction({{{json this}}})"></button>
{{/each}}
现在,像这样做,给我Uncaught SyntaxError: missing ) after argument list
在HTML文件的顶部。
我注意到答案here,所以我尝试使用onclick="myGreatFunction( '{{{json this}}}' )"
,它在HTML文件末尾给出了错误Uncaught SyntaxError: Unexpected token ILLEGAL
。
使用onclick="myGreatFunction( '{{json this}}' )"
,按钮只会在点击时消失。
有没有人看到我错过的东西,还是有另一种方法可以做到这一点?我想把对象添加到模板中的某个div /按钮,然后为从模板中获取值的点击添加一个jQuery-listener,但这看起来很丑陋且不清楚。
有小费吗?非常感谢所有帮助 - 提前感谢。
更新:似乎问题是,正如Hacketo在下面提到的那样,输出的JSON有点搞砸了。我在我的代码中检查了一个元素:
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"}')"
(为方便起见,多行打破)。
现在我只需要找出让JSON看起来正确的东西。
这是因为JSON.stringify
返回一个JSON字符串并包含"
。
目前,您的模板可能如下所示:
<button onclick="myGreatFunction({{{json this}}})"></button>
编译:
<button onclick="myGreatFunction({"foo":"bar"})"></button>
^ ^ ^ ^ ^ ^
而这个结果如同
参数列表后面的Uncaught SyntaxError:missing)
你需要逃脱那些"
,你可以在你的助手中做到这一点
Handlebars.registerHelper('json', function(context) {
return JSON.stringify(context).replace(/"/g, '"');
});
这将导致
<button onclick="myGreatFunction({"foo":"bar"})"></button>
只需取出额外的支架。如果你让Handlebars进行HTML转义(它将自动在常规的{{json this}}
调用中),它也会为你逃脱引号。