Pages

Monday, May 9, 2016

Learning Meteor.js [Part 16]: Select an item on a list

It is time to move on to the brand new 'recipes' page. It will have a similar paged and searchable list of items, in this case recipes, but now the user will be able to click on each recipe and see the details of it.

In this post I will write about changing the UI to show which item is selected and I will leave the master/detail portion for later. First, let's store the id for each item on each HTML node so that it can be accessed later in the event handler:
{{#each recipe in recipes}}
  <li class="list-group-item recipe-item" data-id="{{recipe._id}}"></li>
{{/each}}

Then, handle the event when an item is clicked, extract the id from the HTML node and update a reactive-var with it.
Template.recipesListPart.events({
    'click .recipe-item': function(event, template) {
        var recipeId = $(event.currentTarget).data('id');
        template.selectedItem.set(recipeId);
    }
});

Next, expose an 'isSelected' helper that the view markup can query to modify the CSS class of the element.
Template.recipesListPart.helpers({
    isSelected(item) {
        return item['_id'] === Template.instance().selectedItem.get();
    }
});

Last, use the new helper to conditionally add the CSS class for the selected recipe.
{{#each recipe in recipes}}
  <li class="list-group-item recipe-item {{#if isSelected recipe}}selected{{/if}}" data-id="{{recipe._id}}"></li>
{{/each}}

That's all there is to it. The tutorials that I found say to have the helper return the class name to avoid writing {{#if}} statements in the view, but I prefer to keep CSS class names directly in the view markup for readability. You can use this tag to follow along with the source or view the live demo.

2 comments:

  1. hello and I tried your code and when I click on the item does not assign the data-id or selection marks the Might help

    ReplyDelete
  2. Hello, you can view the latest code in the bitbucket repository that I linked.

    ReplyDelete

Note: Only a member of this blog may post a comment.