简体   繁体   中英

MeteorJS: resubscribe/refresh a Collection?

I'm currently working on my meteor project and I'm not quite understanding what the Meteor way for my problem is.

I have a subscription which is initially called on pageload. I subscribe the following publication without any parameters:

Meteor.publish('testCollection', function(searchitem){
    if(searchitem){
        return testCollection.find({name:searchitem});
    }
    else{
        return testCollection.find({},{
            sort: { rating: -1 },
            limit: 5,
            fields: {
                _id:1,
                name:1,
                description:1
            }
        });
    }
});

This works quite well and I get my results from the else-case.
But I want the user to be able to search in this collection for a name. So my idea of refreshing is to use when submitting searchbutton:

Meteor.subscribe("testCollection","abc");

But this is not refreshing my clientside testCollection. How can I achieve this? Do I have to unsubcribe and subscribe again, if yes: how?

The key here is to limit the data sent (and possibly stored) at the client, by always limiting the result.

In short it's all about re-subscribing to the publication. This can be done in a number of ways, but the simplest (and in my oppinion most elegant) is to use autorun with an reactive source such as Session or ReactiveVar . Whenever this source is changed, a new subscribe is triggered and the previous is canceled.

From Meteor docs: http://docs.meteor.com/#/full/meteor_subscribe

If you call Meteor.subscribe within a reactive computation, for example using Tracker.autorun, the subscription will automatically be cancelled when the computation is invalidated or stopped; it's not necessary to call stop on subscriptions made from inside autorun.

Your code for re-subscribing could look something like this:

Tracker.autorun(function() {  
  if (Session.get('someCustomQuery'))
    Meteor.subscribe('testCollection', Session.get('someCustomQuery'));
});

I'll recommend this tutorial by David Burles:

http://meteorcapture.com/simple-search-pattern/

Example-code with ReactiveVar, triggered by event:

Template.myTemplate.rendered = function(){
  var self = this;

  Tracker.autorun(function() {
    if (self.searchQuery.get())
    {
      var queryOptions = {
        query: self.searchQuery.get()
      };

      Meteor.subscribe('testCollection', queryOptions);
    }
  });
}

Template.myTemplate.created = function(){
  this.searchQuery = new ReactiveVar('');
};

Template.myTemplate.events({
  'keyup [type=search]': function(event, template) {
    template.searchQuery.set(event.target.value);
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM