如何在流星方法模拟之外运行代码

时间:2016-10-14 14:12:03

标签: javascript meteor meteor-blaze ddp

我的Meteor js应用程序中有一个非常有趣的问题:当我在模板的onCreated方法中调用meteor方法时,该方法调用的回调有时会立即返回undefined作为结果。事实证明,这是因为模板是在运行流星方法模拟时创建的。

两个问题:

  1. 这是一个错误吗?这肯定不是我所期望的行为。
  2. 如何在不使用像setTimeout这样的奇怪黑客的情况下解决这个问题(并且方法模拟中允许Meteor.setTimeout不允许这样做?)
  3. 一些代码:

    // My Template (Not my real code, just to demonstrate)
    Template.saying.onCreated(() => {
      var tmpl = Template.instance();
      tmpl.saying = new ReactiveVar();
    
      Meteor.call('getSaying', (err, saying) => {
        // If called inside of a simulation, saying is null
        tmpl.saying.set(saying);
      });
    });
    
    
    // Assume that the above template is used in an {{each}} block
    // and somewhere in my code I call this
    Items.insert({});
    
    // Because Items.insert wraps a meteor method which also runs as a
    // simulation on the client, then the Template.saying.onCreated
    // callback will be called in the context of an active simulation,
    // which means that 'getSaying' method call will return immediately
    // with undefined as the result.
    

1 个答案:

答案 0 :(得分:0)

避免模拟的两种可能性:

  1. 在仅服务器端文件中定义方法
  2. 使用isClient。运行模拟时,它将评估为真

    if (Meteor.isClient) {
    // on the client, the return value of a stub is ignored
    return;
    }