【问题标题】:How to reactively call a Meteor method referenced by a reactive variable?如何反应性地调用反应性变量引用的 Meteor 方法?
【发布时间】:2016-03-02 17:11:19
【问题描述】:

我正在尝试调用 Meteor 方法,而不是使用硬编码字符串,而是使用包含其名称的 Session 变量。当Session 值通过Session.set 更改时,它只工作一次,但不会重新运行该方法。

服务器代码:

Meteor.methods({
  hello: function () {
    console.log("hello");
  },
  hi: function () {
    console.log("hi");
  }
});

客户端代码:

Session.set('say', 'hi');
Meteor.call(Session.get('say'));  // console prints hi
Session.set('say', 'hello');      // console is not printing, expected hello

如何在 Session 值更改后响应式地调用“新”方法?

【问题讨论】:

    标签: javascript meteor meteor-methods


    【解决方案1】:

    您需要一个反应式上下文来实现这种自制的反应性。
    您可以通过Tracker.autorun 简单地实现这一点:

    Session.set('say', 'hi');
    
    Tracker.autorun(function callSayMethod() {
      Meteor.call(
        Session.get('say')
      );
    });
    
    Meteor.setTimeout(
      () => Session.set('say', 'hello'),
      2000
    );
    

    空格键template helpers 使用这种上下文来实现模板中的反应性。

    请注意,这里不需要Session。一个简单的ReactiveVar 就足够了:

    const say = new ReactiveVar('hi');
    
    Tracker.autorun(function callSayMethod() {
      Meteor.call(
        say.get()
      );
    });
    
    Meteor.setTimeout(
      () => say.set('hello'),
      2000
    );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-22
      • 1970-01-01
      • 2020-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-29
      • 2016-06-21
      相关资源
      最近更新 更多