Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FB.api() calls inside underscore template

The underscore template documentation suggest the following should be possible, yet it is not working for me. Executing the template simply returns nothing for this.

<% FB.api('/me', function(response){ %>
<%= response.name %>
<% }); %>
like image 779
Michael B Avatar asked Jul 25 '26 09:07

Michael B


1 Answers

That's a perfectly valid template; in fact, the compiled JavaScript version looks like this (reformatted for readability):

function(obj) {
    var __p = '';
    var print = function() { __p += Array.prototype.join.call(arguments, '') };
    with(obj || {}) {
        __p += '\n';
        FB.api('/me', function(response) { 
            __p += '\n' + response.name + '\n';
        }); 
        __p += '\n';
    }
    return __p;
}

And there's nothing wrong with that. BTW, you can look at the source attribute of a compiled Underscore template if you want to see the JavaScript for the template:

var t = _.template(raw_template);
console.log(t.source);

However, it won't do what you're expecting it to do. Your problem is that the FB.api call is an AJAX call and A stands for asynchronous. So by the time your callback gets called (i.e. <%= response.name %> is executed), the template will have been converted to HTML and added to the DOM and nothing will be looking at the __p variable anymore. The sequence looks something like this:

  1. Compile the template and call the compiled template function.
  2. FB.api gets called.
  3. The template function returns some HTML.
  4. The HTML from 3 is added to the DOM.
  5. Time passes.
  6. Facebook responds and your FB.api callback gets called.
  7. response.name is appended to the __p buffer.

You're going to have to turn your logic inside out a bit. Your FB.api call should be outside your template:

var t = _.template(...);
FB.api('/mu', function(response) {
    var html = t({ response: response });
    // Somehow add html to the DOM
});

so that you don't try to use the template until all the data is ready.

like image 55
mu is too short Avatar answered Jul 28 '26 00:07

mu is too short



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!