Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Meteor: how to access parent properties within nested templates?

Tags:

meteor

I am getting started with Meteor, and adapting the todo example to include nested tag groups. I have the following HTML, which outputs each name of each tag group, plus the list of tags in that each group:

  <template name="tag_filter">
    {{#each tag_types }}
      {{ tag_name }}
      {{#each values }}
        <div data-taggroup="{{ ../tag_name }}">
        {{ name }} ({{ count }})
        </div>
      {{/each}} 
    {{/each}}
</template>

My question is this: how do I adapt the event handler for clicks on the tags to access the value of the parent group's tag_name? (i.e. the data from the outer each loop).

Currently I have the code below, but this object only gives me access to name and count.

Template.tag_filter.events({
  'mousedown .tag': function () {
    console.log('tag mousedown', this);
    // How do I get the value of tag_name?
  }
});

As you can see, I've used Handlebars parent paths to add a data-taggroup attribute containing the name, but I'm not sure how to access that from within the event handler.

I think this question is related, but I don't understand the OP's solution (partly because I'm not using Coffeescript). There's also an closed Meteor issue which is related.

like image 504
Richard Avatar asked Oct 26 '12 17:10

Richard


2 Answers

I found the solution to access parent data:

Template.nestedTemplate.events({
    'click a.class':function(event,template){
        var parentID = template.data._id;
        console.log(parentID);
    }
});

The .events handler function receives two arguments: event, an object with information about the event, and template, a template instance for the template where the handler is defined. Took me a really long time to figure this one out. Don't use the handlebars solution, it shows your data!

like image 187
Marz Avatar answered Sep 29 '22 10:09

Marz


I'm not sure whether you can get parent template data, but in your event handler you can access DOM elements: event.currentTarget will get the clicked element. Then just use jQuery to access attributes. If needed, event.currentTarget.parentNode will get the parent element in the DOM.

Ex: I don't know where you put the tag class, but let's say it's the class of your div where data-taggroup is defined. Then you could get the tag name using:

$(event.currentTarget).attr('data-taggroup')
like image 28
Gwened Avatar answered Sep 29 '22 12:09

Gwened