【发布时间】:2013-02-14 17:49:18
【问题描述】:
关于 Meteor 中模板的事件处理程序上下文的快速问题(使用 Handlebars)。
- 在关于模板实例的文档部分 (http://docs.meteor.com/#template_inst) 中提到“模板实例对象在创建、渲染和销毁的模板回调中作为 this 的值找到,作为事件处理程序的参数“
- 在模板部分 (http://docs.meteor.com/#templates) 中显示“最后,您可以在模板函数上使用事件声明来设置事件处理程序表。该格式记录在事件映射中。事件处理程序的 this 参数将是触发事件的元素的数据上下文。"
嗯,这只是部分正确。让我们使用文档中的一个示例:
<template name="scores">
{{#each player}}
{{> playerScore}}
{{/each}}
</template>
<template name="playerScore">
<div>{{name}}: {{score}}
<span class="givePoints">Give points</span>
</div>
</template
Template.playerScore.events({
'click .givePoints': function () {
Users.update({_id: this._id}, {$inc: {score: 2}});
});
这里的“click .givePoints”事件处理程序的“this”上下文确实是 playerScore 的模板实例。让我们修改html:
<template name="scores">
<span class="click-me">Y U NO click me?<span>
{{#each player}}
{{> playerScore}}
{{/each}}
</template>
<template name="playerScore">
<div>{{name}}: {{score}}
<span class="givePoints">Give points</span>
</div>
</template>
...并在分数模板上为 .click-me 添加事件处理程序:
Template.scores.events({
'click .click-me': function () {
console.log(this);
}
});
现在,如果您单击跨度,您会记录什么?窗口对象!我期望得到什么?模板对象!或者可能是数据上下文,但两者都不是。然而,在回调内部(例如 Template.scores.rendered = function(){ ... }),“this”的上下文始终是模板实例。
我想我真正的问题是:这是否与此有关
- Handlebars、Meteor 或介于两者之间的某个错误?
- 关于模板的文档有些不完整?
- 我完全误解了文档或不理解一些基本的东西 关于 Meteor 或 Handlebars?
谢谢!
【问题讨论】:
-
这是一个正确的问题。我一直使用
function(event,template)访问事件中的数据,然后通过template.data。 -
希望我能投票两次
-
@ТаняТ。您可以像我一样将问题标记为收藏 ;-)
标签: javascript meteor handlebars.js