Reputation: 63717
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.
Upvotes: 1
Views: 563
Reputation: 932
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');
}
});
Upvotes: 1
Reputation: 161
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
}
});
Upvotes: 2