【问题标题】:Meteor, stub method and meteor methodsMeteor、存根方法和流星方法
【发布时间】:2014-02-17 14:27:00
【问题描述】:

我正在使用流星, 我的 html 中有一个车把标签

{{displayResult}}

在我的客户端 JS 文件中,我编写了这样的帮助程序和存根方法

辅助功能 *编辑*

displayResult:function(){
    var abc;
    var apiResultDependency = new Deps.Dependency();  
    Meteor.call('apiresult',function(e,result){
   abc=result;
   apiResultDependency.changed();                                           
    });                                     
                                                console.log(abc);                                                  
                                             console.log(result);

apiResultDependency.depend();
    return abc;//returning nothing
}

存根方法

Meteor.startup(function(){              
    return Meteor.methods({
        apiresult:function(){
            console.log("loading...");
        }
    });
});

而我的服务器代码与一个 API 连接并延迟结果,我的代码是

apiresult:function(){
  var response = returnAllResult();//this gets the result from outside func. working good
  return response;
}

我想从服务器端函数中获取结果,我想在 html 文件中显示 如何接收和显示它。我的网页中没有任何内容。在我的控制台中,它正在打印结果。

【问题讨论】:

    标签: javascript meteor


    【解决方案1】:

    问题是当数据从服务器到达时,您的模板不会重新呈现。解决此问题的最简单方法是使用响应式数据源模式(查看 here),因此在您的客户端代码中,您需要添加如下内容:

    var apiResultDependency = new Deps.Dependency();
    var abc;
    

    你的助手可能看起来像这样:

    displayResult: function() {
      if (abc === undefined) {
        Meteor.call('apiresult', function(e,result) {
          abc = result; // make sure this is not undefined to prevent infinite loop
          apiResultDependency.changed();
        });
      }
      apiResultDependency.depend();
      return abc;
    }
    

    【讨论】:

    • 这是我调用服务器端方法时的主要问题,它首先将 abc 变量设置为未定义。我现在正在循环运行。
    • 是的,我明白了。你有没有检查我的建议?我很确定这应该可以正常工作。
    • 我写了一个存根方法,它返回“正在加载..”字符串,但它不起作用,结果仍然返回未定义的值。如何克服它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-08
    • 2014-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-06
    相关资源
    最近更新 更多