Pages

Wednesday, July 6, 2016

Learning Meteor.js [Part 34]: Update collections in real time when other users modify them

This is one of the impressive capabilities of Meteor: automatic push of updates to all connected clients. For today's feature I want to allow users to create ingredients which anybody using the application can use to build their own recipes where we will see this in action.

First, create the server's validated method:
export const addIngredient = new ValidatedMethod({
    name: 'ingredients.add',
    validate: new SimpleSchema({
        name: { type: String },
        imageUrl: { type: String, optional: true, defaultValue: '/images/default-ingredient.png' }
    }).validator({ clean: true }),
    mixins: [Mixins.authenticated],
    run({ name, imageUrl }) {
        Ingredients.insert({
            name: name,
            imageUrl: imageUrl,
            userId: this.userId
        });
    }
});

Next, in the view, only if the user is authenticated show an 'Add' button that will open a modal dialog to create an ingredient. This can be done by using the 'currentUser' built-in template helper. In this case I used Bootstrap's modal dialog for simplicity.
{{#if currentUser}}
   <a href="#" class="btn btn-default btn-block btn-primary" data-toggle="modal" data-target="#addIngredientModal">Add</a>
{{/if}}

Finally, invoke the server method when the user clicks the 'Save' button and dismiss the dialog when the operation is done:
Template.ingredientsListPart.events({
    'click .ingredient-add': function(event, template) {
        event.preventDefault();

        var $name = $('#inputIngredientName');
        var $url = $('#inputIngredientImageUrl');

        IngredientMethods.addIngredient.call({ name:  $name.val(), imageUrl: $url.val() }, function(err, res) {
            if (err) {
                alert(err);
            } else {
                $('#addIngredientModal').modal('hide');
            }
        });
    }
});

Notice in the screen shot below that as soon as one user creates an ingredient, all other users will automatically see it. You can check the code up to this point by using this commit or visit the live demo.


No comments:

Post a Comment

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