Meteor.call from a Handlebars block helper

前端 未结 1 1121
面向向阳花
面向向阳花 2021-01-13 16:10

I am trying to use a Meteor.call function within a Handlebars block helper

Handlebars.registerHelper(\'get_handle\', function(profileId, name) {         


        
相关标签:
1条回答
  • 2021-01-13 16:41

    You can't use Meteor.call in a handlebars block with the paradigm above, primarily because of javascript's asynchronous design, by the time a value is received from the server, the return value has already been returned.

    You can however pass it through using a Session variable:

    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>');
        }
    });
    

    Also be careful with trying to use have so many Meteor.call for each profileId and name (if you're using this in some sort of list or something) when you could request the data in one bulk request.

    Hacky way

    You can still do it the way you intend, but I would advise against it. I think its a bit inefficient.

    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..."
         }
    });
    
    0 讨论(0)
提交回复
热议问题