如何在事件上获取流星中的父数据上下文 [英] How to Get Parent Data Context in Meteor on an Event
问题描述
我正在开发一个简单的流星抽认卡应用程序.有一系列问题,每个问题包括:文本,正确答案,错误答案.
I'm working on a simple meteor flashcard application. There is a collection of Questions each with: text, right_answer, wrong_answers.
将答案串联到一个数组中并随机排列,然后模板列出一个问题和可能的答案.当用户单击答案时,如何通过事件获取JS中的父数据上下文.
The answers are concatenated into an array and shuffled then the template lays out a question and possible answers. When a user clicks the answer, from the event how do I get the parent data context in the JS.
类似的东西:
<button type="button" question="{{../_id}}" class="btn btn-default answer">
{{this}} {{#with ../this}}{{this._id}}{{/with}}
</button>
可以在模板中显示父问题ID,但是如何正确执行此操作.我们的目标是拥有一个捕获事件的功能,并将答案与"right_answer"进行比较以确保是否相等,并给出一个可行的点.谢谢!
works to show parent question ID in the template, but how do I do this properly. The goal is to have a function that grabs the event and compares the answer to the "right_answer" for equality and gives you a point if it works. Thanks!
最终想出了这个解决方案,但我不太喜欢它或认为它是正确的:
Eventually came up with this solution, but I don't really like it or think it is correct:
{{each}}
{{#with ../this}}
<button type="button" question="{{../_id}}" class="btn btn-default answer">X</span></button>
{{/with}}
{{this}}
{{/each}}
推荐答案
我通常会这样做:
Template.myTemplate.answers = function () {
var self = this;
// assume that this.answers is a list of possible answers
return _.map(this.answers, function (answer) {
return _.extend(answer, {
questionId: self._id,
});
});
}
那么您就可以开始使用了,在您的模板中,您可以执行以下操作:
Then you're good to go and in your template you can do things like:
<template name="myTemplate">
{{#each answers}}
<button data-question="questionId">...</button>
{{/each}}
</template>
顺便说一句:注意,根据标准,在html
元素上使用question
属性是不正确的.您应该始终在自定义标签的前面加上data-
.
BTW: Note, that using question
attribute on html
element is incorrect according to the standard. You should always prefix your custom tags with data-
.
还请注意,如果您将事件附加到模板上,如下所示:
Also note, that if you attach events to your templates like this:
Template.myTemplate.events({
'click button': function (event, template) {
// ...
},
});
然后在事件回调中,您可以访问this
和template.data
,其中this
表示呈现button
元素的上下文,而template.data
则是附加到模板实例的数据上下文,因此实际上或多或少是您的父级上下文".
then in the event callback you have access to this
, which represents the context where the button
element was rendered, as well as template.data
which is the data context attached to your template instance, so in fact this is more or less your "parent context".
请注意,新的模板引擎即blaze
允许我们在模板中使用点表示法,因此不再需要上述方法,并且{{../_id}}
完全可以.
Note that the new templating engine, i.e. blaze
, allows us to use dot notation in templates, so the method I described above is no longer needed and {{../_id}}
is totally fine.
这篇关于如何在事件上获取流星中的父数据上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!