简体   繁体   English

Meteor.js服务器端代码可以对客户端上的会话变量做出反应

[英]Can Meteor.js Server side code react to Session variables on Client

Is there a way to let code on the server react to a Session.variable on the client? 有没有办法让服务器上的代码对客户端上的Session.variable做出反应?

eg: 例如:

if(Meteor.isClient() {
    Template.main.events({
        'click #appleBtn': function() {
            Session.set('fruit', 'apples')
        }
    })
}


if(Meteor.isServer) {
    if(Session.get('fruit') == 'apples') {
        doSomething()
    } else {
        doAnotherThing()
    }   
}

My initial idea is to have a clientside code continuously send the value of the session variable to the server via a method call, but that doesnt seem too efficient. 我最初的想法是让客户端代码通过方法调用不断地将会话变量的值发送到服务器,但这看起来效率太高。

Sessions don't work on server-side, but your initial idea is a good start. 会话在服务器端不起作用,但您最初的想法是一个良好的开端。

Instead of continuously sending that session value just have a template helper on the client that gets the session value and calls a Meteor method with that value. 而不是连续发送该会话值只是在客户端上有一个模板助手获取会话值并使用该值调用Meteor方法。 This way only when an update happens to the session variable will that client helper react to the change and call the Meteor method with updated values. 这种方式只有在会话变量发生更新时,客户端帮助程序才会对更改做出反应并使用更新的值调用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
    }
});

Have you tried Tracker.autorun ? 你试过Tracker.autorun吗?

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

The method will only be called when the Session var changes (after running once with the initial value of Session.get('fruit')) 只有当Session var发生变化时(在使用Session.get('fruit')的初始值运行一次之后)才会调用该方法

On the server you'd do: 在服务器上你做的:

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

EDIT: RE my comment below, an example of doing this entirely inside a single template: 编辑:我的评论如下,一个完全在单个模板中执行此操作的示例:

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.

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