How to Get Parent Data Context in Meteor on an Event

后端 未结 2 891
小蘑菇
小蘑菇 2021-01-02 15:53

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

相关标签:
2条回答
  • 2021-01-02 16:33

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

    0 讨论(0)
  • 2021-01-02 16:45

    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.

    0 讨论(0)
提交回复
热议问题