Reputation: 1272
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
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
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
i
in the loop has the value of end of loopi
which is called with the value of the loopUpvotes: 2