[英]Can Meteor.js Server side code react to Session variables on Client
有没有办法让服务器上的代码对客户端上的Session.variable做出反应?
例如:
if(Meteor.isClient() {
Template.main.events({
'click #appleBtn': function() {
Session.set('fruit', 'apples')
}
})
}
if(Meteor.isServer) {
if(Session.get('fruit') == 'apples') {
doSomething()
} else {
doAnotherThing()
}
}
我最初的想法是让客户端代码通过方法调用不断地将会话变量的值发送到服务器,但这看起来效率太高。
会话在服务器端不起作用,但您最初的想法是一个良好的开端。
而不是连续发送该会话值只是在客户端上有一个模板助手获取会话值并使用该值调用Meteor方法。 这种方式只有在会话变量发生更新时,客户端帮助程序才会对更改做出反应并使用更新的值调用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 var发生变化时(在使用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');
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.