我目前正在开发 Meteor 项目,但不太了解解决我的问题的 Meteor 方法是什么。
我有一个订阅,最初在页面加载时调用。我订阅以下出版物,不带任何参数:
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
}
});
}
});
这工作得很好,我从 else-case 中得到了结果。
但我希望用户能够在此集合中搜索名称。
所以我的刷新思路是在提交searchbutton时使用:
Meteor.subscribe("testCollection","abc");
但这并没有刷新我的客户端 testCollection。 我怎样才能实现这个目标?我是否必须取消订阅并再次订阅(如果是):如何?
最佳答案
这里的关键是通过始终限制结果来限制在客户端发送(并可能存储)的数据。
简而言之,这就是重新订阅该出版物。这可以通过多种方式完成,但最简单的(在我看来也是最优雅的)是将 autorun 与 react 源一起使用,例如 Session或ReactiveVar 。每当此源发生更改时,都会触发新的订阅并取消先前的订阅。
来自 Meteor 文档: 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.
您的重新订阅代码可能如下所示:
Tracker.autorun(function() {
if (Session.get('someCustomQuery'))
Meteor.subscribe('testCollection', Session.get('someCustomQuery'));
});
我会推荐 David Burles 的本教程:
http://meteorcapture.com/simple-search-pattern/
带有 ReactiveVar 的示例代码,由事件触发:
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);
}
});
关于javascript - meteor JS : resubscribe/refresh a Collection?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32456174/