dtgee
dtgee

Reputation: 1272

How to pass a variable to a function that's part of the parameters of a function call?

for (var i = 0; i < json.length; i++) {
    $.Mustache.load('/mustaches.php', function(i) {
         //Do Something
    });
}

How do I pass the var i to the function in this case?

EDIT: Sorry I don't actually want to make the Mustache.load call too many times. Only once. How can I do that?

Upvotes: 0

Views: 103

Answers (2)

danielepolencic
danielepolencic

Reputation: 5163

An elegant way to solve your question would be using the bind method.

for (var i = 0; i < json.length; i++) {
    $.Mustache.load('/mustaches.php', function(i) {
         //Do Something
    }.bind(this, i));
}

the bind method returns a new function with a new context (in this case this) and applies one (or more) argument(s) to your function (i in this particular case). You can find more about bind and currying here.

EDIT. You can optimise your loop by loading the template only once. In fact, $.Mustache.load fetches /mustache.php on each cycle of the loop. Also, because the function asynchronously fetches the template with AJAX, you might get not consistent ordering in your template (one response may take longer than others). The fix is pretty straightforward: we load the template and then we iterate through the loop.

$.get('/mustache.php').done(function(template){
  $.Mustache.add('my-template', template);
  for (var i = 0, len = json.length; i < len; ++i) {
    var rendered_template = $.Mustache.render('my-template', {
      i: i,
      ...
    });
  }
});

Upvotes: 0

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382132

This is a little more complicated than you might think, as you must ensure you pass the right value of i, so that the callback doesn't use the value of end of loop.

for (var i = 0; i < json.length; i++) {
    (function(i){
        $.Mustache.load('/mustaches.php', function() {
            // use i. Call a function if necessary
            //Do Something
        });
    })(i);
}

About the callback term : it refers to a function you pass as argument so that the function you call can call it back.

To understand the code I wrote, you must

  • understand that the callback is called later, when the loop has finished and so when i in the loop has the value of end of loop
  • that the scope of a non global variable is the function call in which it is defined. That's why there's this intermediate function : to define another variable i which is called with the value of the loop

Upvotes: 2

Related Questions