Couple things to note. By doing:
Meteor.publish 'activities', ->
Activities.find(task: 'Test')
This will limit your subscription to only those that met that filter. So if you’re trying to filter for something else (like task: 'Foo'
) it won’t work because your publication is already only returning a filtered set of documents. This why when you console logged Activities.find({task: 'Test'}).fetch()
you only saw documents that had task: 'Test'
.
Also, you can’t bind a click
event inside a Helper. So you’ll need to separate out what the helper does vs the click event.
Here’s one way to do what you’re after:
Meteor.publish('activities', function(keyword) { // allow keyword to be passed in
check(keyword, String); // make sure you're using the check package to help with security/sanitization of client-inputted data.
if(keyword){
return Activities.find({ task: keyword }); // if keyword, return the filtered set
} else {
return Activities.find({}); // maybe by default you're just returning everything. up to you.
}
});
Then in your template:
Template.dashboard.onCreated(function() {
Session.set('filtered-task', null); // use a Session var
this.subscribe('activities');
});
In your helper:
Template.dashboard.helpers({
someHelper: function(){ // not sure how you named your helper, but it needs a name that you'll then use in your Blaze template
var data = Activities.find({ task: Session.get('filtered-task') });
// by default, the Session variable is "null", so this won't filter anything
if(data.count()){
return data;
}
}
});
Then in your event:
Template.dashboard.events({
'click .ButtonDemo': function (e) {
e.preventDefault();
console.log("Successful click");
Session.set('filtered-task', 'Test'); // or you could get the "Test" string from a dropdown or checkbox and use that rather than hard-coding it. but for testing purposes this should do the trick.
}
});
To recap, the Publication I defined just returns everything without filter. In the Template, you’ll subscribe to “activities”, and then in the helper you’ll return the document set filtered by Session.get('filtered-task')
(which is null to start with). Then in your event, you can change the value of the Session variable, which will dynamically trigger the helper to return the newly filtered data.
Fwiw: use of the Session variables this way can be somewhat controversial in the Meteor community, as some denounce it while others find it works great. From my point of view, in 4+ years of working with Meteor I’ve found Session vars to work great, hence the proposed usage here.