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.
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
ReplyDeleteHello, you can view the latest code in the bitbucket repository that I linked.
ReplyDelete