Search code examples
mongodbmeteormeteor-blaze

On click how to only show collection entries with task: 'Test'?


The code below only loads data where task has the entry ‘Test’.

Meteor.publish 'activities', ->
  Activities.find(task: 'Test')

How can I achieve the same when a button is clicked when the code is:

Meteor.publish 'activities', ->
  Activities.find()

Here’s my code so far:

Client:

Template.dashboard.events({
  'click .ButtonDemo': function (e) {
    e.preventDefault();
    console.log("Successful click");
    activities: Activities.find({task: 'Test'}).fetch()
  }
});

Router:

@route "dashboard",
path: "/dashboard"
waitOn: ->
  [
    subs.subscribe 'activities'
  ]
data: ->
  activities: Activities.find({},{sort: {createdAt: -1}}).fetch()

Solution

  • Add the (core) reactive-var package to your project: meteor add reactive-var.

    Then:

    On the server, change your publication to take an argument:

    Meteor.publish('activities', (filter = {}) => { return Activities.find(filter); });
    

    On the client, declare the reactive variable:

    const filter = new ReactiveVar({})
    

    Change your subscription to take that variable as argument:

    Meteor.subscribe('activities', filter);
    

    and set that variable on click:

    Template.dashboard.events({
      'click .ButtonDemo': () => {
        console.log("Successful click");
        filter.set({task: 'Test'});
        return false;
      }
    });