Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Get Parent Data Context in Meteor on an Event

Tags:

meteor

I'm working on a simple meteor flashcard application. There is a collection of Questions each with: text, right_answer, wrong_answers.

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.

Something like:

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

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}}
like image 347
Brendan Levy Avatar asked Oct 28 '13 01:10

Brendan Levy


2 Answers

I usually 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'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>

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) {
       // ...
   },
});

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".

EDIT

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.

like image 156
Tomasz Lenarcik Avatar answered Dec 03 '22 04:12

Tomasz Lenarcik


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

like image 20
Loren Avatar answered Dec 03 '22 03:12

Loren