How to get the parent data context in Meteor at an event

I am working on a simple flash card application. There is a set of Questions, each of which is text, right_answer, wrong_answers.

Answers are concatenated into an array and shuffled, then the template asks the question and possible answers. When the user clicks on the response from the event, how do I get the context of the parent data in JS.

Sort of:

<button type="button" question="{{../_id}}" class="btn btn-default answer"> {{this}} {{#with ../this}}{{this._id}}{{/with}} </button> 

works to show the parent id of the question in the template, but how to do it correctly. The goal is to have a function that captures the event and compares the answer with "right_answer" on equality and gives you a point if it works. Thanks!

In the end, I came up with this solution, but I don’t really like it, or I think it’s right:

 {{each}} {{#with ../this}} <button type="button" question="{{../_id}}" class="btn btn-default answer">X</span></button> {{/with}} {{this}} {{/each}} 
+6
source share
2 answers

Usually I do something like this:

 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 are good to go, and in your template you can do things like:

 <template name="myTemplate"> {{#each answers}} <button data-question="questionId">...</button> {{/each}} </template> 

BTW: Please note that the use of the attribute question in the element html incorrect in accordance with the standard. You should always attribute your own data- tags.

Also note that if you attach events to your templates as follows:

 Template.myTemplate.events({ 'click button': function (event, template) { // ... }, }); 

then in the event callback you have access to this , which represents the context in which the button element was displayed, as well as template.data , which is the data context attached to your template instance, so this is actually more or less yours parent context. "

EDIT

Please note that the new template engine, i.e. blaze , allows us to use dot notation in templates, so the method described above is no longer needed, and {{../_id}} completely beautiful.

+5
source

You can access Template.parentData(n) in event handlers: http://docs.meteor.com/#/full/template_parentdata

+5
source

Source: https://habr.com/ru/post/956840/


All Articles