Meteor.js服务器端代码可以响应客户端上的会话variables

有没有办法让服务器上的代码响应客户端上的Session.Valiable?

例如:

if(Meteor.isClient() { Template.main.events({ 'click #appleBtn': function() { Session.set('fruit', 'apples') } }) } if(Meteor.isServer) { if(Session.get('fruit') == 'apples') { doSomething() } else { doAnotherThing() } } 

我最初的想法是有一个客户端代码不断发送会话variables的值通过方法调用的服务器,但这似乎不是太高效。

会话在服务器端不起作用,但您的初始想法是一个好的开始。

而不是连续发送该会话值,只需要在获取会话值的客户端上有一个模板帮助器,并使用该值调用Meteor方法。 只有当会话variables发生更新时,客户端助手才会对更改作出反应,并使用更新后的值调用Meteor方法。

 // Client Template.main.helpers({ reactiveHelper: { var reactiveValue = Session.get('fruit'); Meteor.call('someMethod', reactiveValue); } }); // Templates where you want this to happen {{reactiveHelper}} // Server Meteor.methods({ 'someMethod': function(reactiveValue) { // Server code that reacts to client session changes } }); 

你有没有试过Tracker.autorun

 Tracker.autorun(function () { Meteor.call('someMethod', Session.get('fruit'), function (err, res) { // do something with the result... }); }); 

这个方法只会在Session的变化(Session.get('fruit')初始值运行一次)之后被调用。

在服务器上你会做:

 Meteor.methods({ someMethod: function (fruit) { if (fruit === 'apple') { doSomething(); } else { doSomethingElse(); } } }); 

编辑:下面我的评论,这完全在一个单一的模板内的一个例子:

 Template.MyTemplate.onCreated(function () { this.fruit = new ReactiveVar('orange'); var instance = this; instance.autorun(function() { Meteor.call('myMethod', instance.fruit.get(), function (err, res) { // do something? }); }); }); Template.MyTemplate.events({ 'click #myButton': function (event, tmpl) { tmpl.fruit.set('apple'); } });