FindFromPublication.publish('ingredients', function(limit, onlyMine, nameQuery) { var query = {}; var options = { sort: { name: 1 }, limit: limit }; if (nameQuery) { query['name'] = { $regex: nameQuery, $options: 'i' }; } if (onlyMine && this.userId) { query['userId'] = this.userId; } return Ingredients.find(query, options); });
Given how MongoDb's query syntax work, we can conditionally add fields to the query object and they will be treated as a logical 'AND'. Now, on the client a new ReactiveVar is created for the new argument used within an autorun function:
Template.ingredientsListPart.onCreated(function ingredientsListPartOnCreated() { var instance = this; instance.limit = new ReactiveVar(5); instance.query = new ReactiveVar(); instance.onlyMine = new ReactiveVar(false); instance.autorun(function() { var limit = instance.limit.get(); var query = instance.query.get(); var onlyMine = instance.onlyMine.get(); instance.subscribe('ingredients', limit, onlyMine, query); }); });
Finally, a checkbox is added in the UI to toggle the reactive var. Whenever the value changes the autorun function re-executes, which re-subscribes using a different value for the filter.
Template.ingredientsListPart.events({ 'click .ingredient-search-mine': function(event, template) { template.onlyMine.set(event.currentTarget.checked); template.limit.set(5); } });
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.