簡體   English   中英

Meteor.js服務器端代碼可以對客戶端上的會話變量做出反應

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM