【问题标题】:Meteor.call from a Handlebars block helper来自 Handlebars 块助手的 Meteor.call
【发布时间】:2013-03-03 23:02:19
【问题描述】:

我正在尝试在 Handlebars 块助手中使用 Meteor.call 函数

Handlebars.registerHelper('get_handle', function(profileId, name) {
  Meteor.call("getProfileLink", profileId, function(error, result) {
    if (error) {
      return new Handlebars.SafeString('<a href="#">' + name + '</a>');
    } else {
      return new Handlebars.SafeString('<a href="http://twitter.com/' + result + '">' + name + '</a>');
    }
  });
});

我在console.log(result) 中看到正在返回结果,但没有呈现来自此帮助程序的 HTML。但是,当我将相同的 Handlebars.SafeString 返回值从 Meteor.call 中取出时,它可以正常工作。我在这里做错了什么?还是在 Handlebars 块中使用 Meteor.call 不正确?

【问题讨论】:

    标签: meteor


    【解决方案1】:

    您不能在上面的范例中在把手块中使用 Meteor.call,主要是因为 javascript 的异步设计,当从服务器接收到值时,返回值已经返回。

    但是,您可以使用 Session 变量传递它:

    Handlebars.registerHelper('get_handle', profileId, name,  function() {
        return new Handlebars.SafeString(Session.get("get_handle" + profileId + "_" + name));
    
    });
    
    
    //In a meteor.startup or a template.render
    Meteor.call("getProfileLink", profileId, name, function(error, result) {
        if (error) {
           Session.set("get_handle" + profileId + "_" + name, '<a href="#">' + name + '</a>');
        } else {
           Session.set("get_handle" + profileId + "_" + name, '<a href="http://twitter.com/' + result + '">' + name + '</a>');
        }
    });
    

    当您可以在一个批量请求中请求数据时,还要小心尝试为每个 profileId 和名称(如果您在某种列表或其他东西中使用它)使用这么多 Meteor.call

    套路

    您仍然可以按照您的意愿进行操作,但我建议您不要这样做。我觉得效率有点低。

    Handlebars.registerHelper('get_handle', profileId, name,  function() {
        if(Session.get("get_handle" + profileId + "_" + name)) {
            return new Handlebars.SafeString(Session.get("get_handle" + profileId + "_" + name));
        }
        else
        {
            Meteor.call("getProfileLink", profileId, name, function(error, result) {
                if (error) {
                    Session.set("get_handle" + profileId + "_" + name, '<a href="#">' + name + '</a>');
                } else {
                    Session.set("get_handle" + profileId + "_" + name, '<a href="http://twitter.com/' + result + '">' + name + '</a>');
                }
            });
            return "Loading..."
         }
    });
    

    【讨论】:

    • 谢谢阿克沙特。我想我宁愿把它作为一个字段添加到文档中并检索,而不是稍后渲染。
    • 我已经对其进行了修改,并为您添加了一种方法
    • 我认为最简单的方法是在创建文档时存储句柄并在检索列表时呈现它。我之前没有存储句柄字段。不过还是谢谢。我喜欢黑客:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-21
    • 2023-03-30
    相关资源
    最近更新 更多