简体   繁体   中英

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?

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. 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.

// 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(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'))

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');
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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