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,
...
});
}
});