Pages

Wednesday, May 11, 2016

Learning Meteor.js [Part 18]: Hook up the master and details components with messages

Now that postal.js is included the recipe details component needs to subscribe to the 'recipe.selected' message that is triggered by the list component.

First, publish the message when a user clicks on a recipe in the list:
Template.recipesListPart.events({
    'click .recipe-item': function(event, template) {
        var recipeId = $(event.currentTarget).data('id');

        postal.publish({
            topic: 'recipe.selected',
            data: {
                id: recipeId
            }
        });
    }
});

Then subscribe to the topic in the details component and use a ReactiveVar to re-execute the meteor subscription that downloads the recipe document.
Template.recipeDetailsPart.onCreated(function() {
    var template = this;

    template.recipeId = new ReactiveVar();

    template.postalSub = postal.subscribe({
        topic: 'recipe.selected',
        callback: (data) => {
            template.recipeId.set(data.id);
        }
    });

    template.autorun(function() {
        template.subscribe('recipeDetails', template.recipeId.get());
    });
});

Now, to expose the recipe to the view markup, add a helper that returns a mongo cursor that contains the unique document
Template.recipeDetailsPart.helpers({
    recipe() {
        return Recipes.findOne({ '_id': Template.instance().recipeId.get() })
    }
});

Lastly, don't forget to unsubscribe from postal when the template is destroyed
Template.recipeDetailsPart.onDestroyed(function() {
    postal.unsubscribe(this.postalSub);
});

This wraps up the master/detail page of recipes. You can use the same tag as before to look at the whole working feature.

No comments:

Post a Comment

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