所以我正在尝试在 Meteor 中实时搜索一些客户端信息。
我有
Template.userTable.events({
"change #nameSearchBar":function(event){
//console.log(event);
searchText = event.target.value;
filteredUsers = Meteor.users.find({"profile.name":{$regex: (".*"+searchText+".*") } });
console.log(filteredUsers.fetch());
}
});
在我的js中,和
Template.userTable.helpers({
usersOnline: function() {
return filteredUsers;
}
});
还有。我可以在控制台日志中看到 filteredUsers 已更新,但我没有得到列出 usersOnline 的 html 的实时更新 - 相反,我只是得到了所有这些,这就是 usersOnline 通过调用 filteredUsers 初始化的内容= Meteor.users.find().
如何获得所需的实时更新?
最佳答案
您的 filteredUsers
变量不是 react 性的,因此当它发生变化时,没有任何内容告诉 usersOnline
帮助器重新运行。我认为您可以通过以下两种方式之一执行此操作:
使用 ReactiveVar .诚然,我对它们不是很有经验,但我认为您可以将 ReactiveVar 指定为模板的一部分,然后让它观看——类似于:
Template.userTable.created = function() { this.data.filteredUsers = new ReactiveVar(...) // initialize this to whatever } Template.userTable.helpers({ usersOnline: function() { return this.filteredUsers.get(); // pulling from the reactive var rather than a static var } }); Template.userTable.events({ "change #nameSearchBar":function(event){ searchText = event.target.value; // Setting the reactive var should invalidate the "get" in the helper and trigger re-run filteredUsers.set(Meteor.users.find({"profile.name":{$regex: (".*"+searchText+".*") } })); } });
使用 Session variable -- 非常相似,但它可以全局访问,而不是在该模板上设置。默认情况下,所有 session 变量都是响应式(Reactive)的:
Template.userTable.created = function() { Session.setDefault('filteredUsers', ...) // initialize this to whatever } Template.userTable.destroyed = function() { Session.set('filteredUsers', null); // clean up after yourself when you navigate away } Template.userTable.helpers({ usersOnline: function() { return Session.get('filteredUsers'); // pulling from Session var, which is reactive } }); Template.userTable.events({ "change #nameSearchBar":function(event){ searchText = event.target.value; // Setting the Session var should invalidate the "get" in the helper and trigger re-run Session.set('filteredUsers', Meteor.users.find({"profile.name":{$regex: (".*"+searchText+".*") } })); } });
就像我说的,我没有对 ReactiveVars 做太多,但我认为 #1 在技术上是更好的方法,所以我会先尝试一下。
关于javascript - Meteor - 简单的搜索问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29173516/