Bunjip
Bunjip

Reputation: 297

Meteor.js: How to retrieve data attribute of parent element of an event object?

I want to build some kind of interactive week plan. I use an html table for displaying the plan. Each table row corresponds to one day of the week, while each table cell represents a certain part of the day (e.g. 'morning', 'noon' e.t.c.). The table is rendered in a template partial. To interact with each field of the table, I bind data attributes to each . In order to prevent redundancy, I want to bind the respective date to a data attribute of the table rows rather than to each single table cell. My question is, in the event handler of that template, how can I access the data attribute of the corresponding parent table row, if a table cell was clicked?

week-plan.html looks like

<template name="weekPlan">
...
<tbody>
  {{#each daysOfWeek}}
    {{> dayDataRow weekDay=day weekDayDate=date}}
  {{/each}}
</tbody>
...
</template>

day-data-row.html looks like

<template name="dayDataRow">
  <tr class="week-plan--date" data-date="{{weekDayDate}}">
    <td class="week-plan--day">{{weekDay}}</td>
    <td class="week-plan--item" data-my-data="morning"></td> 
    <td class="week-plan--item" data-my-data="noon"></td>
    <td class="week-plan--item" data-my-data="afternoon"></td>
    <td class="week-plan--item" data-my-data="evening"></td>
    <td class="week-plan--item" data-my-data="night"></td>
  </tr>
</template>

week-plan.js looks like:

Template.weekPlan.helpers({
  daysOfWeek: function(){
    var today = new Date();
    var firstOfWeek = today.getDate() - today.getDay() + 1;
    var weekDays =  ['So', 'Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa'];
    weekArray = new Array();
    var row = 0;
    for (row; row < 7; row++){
      var date = new Date(today.setDate(firstOfWeek + row));
      var day = weekDays[date.getDay()];
      weekArray[row] = {'date': date.yyyymmdd(), 'day': day};
    };
    return weekArray;
  }
});

Template.weekPlan.events({
  'click .week-plan--item': function(event, template){
    console.log('Part of day: ' + event.target.dataset.myData);
    // I'm looking for something like...
    console.log('Date of day: ' + event.target.parent.dataset.date);
  }
});

Any help is much appreciated.

Upvotes: 1

Views: 5421

Answers (1)

richsilv
richsilv

Reputation: 8013

This should work:

console.log('Date of day: '
     + $(event.currentTarget).parent('.week-plan--date').data('date'));

Upvotes: 9

Related Questions