(function() {
var content = [
{
title: 'My awesome blog post',
thumbnail: 'images/bane.jpg',
},
{
title: 'My second awesome blog post',
thumbnail: 'images/joker.jpg',
},
],
template = $.trim( $('#blogTemplate').html() ),
frag = '';
$.each( content, function( index, obj ) {
frag +=
template.replace( /{{title}}/ig, obj.title )
.replace( /{{thumbnail}}/ig, obj.thumbnail );
});
$('body').append(frag);
})();
Hello There,
I was just wondering why it is that the code block that is contained within a self invoking anonymous function cannot have the following variable declarations prefixed with the var keyword like so:
var template = $.trim( $('#blogTemplate').html() ),
var frag = '';
Adding the var keyword to the local variables in this function – template and frag seems to break my code and I really don’t understand why, however if I declare template and frag on a global scope outside of the function as shown below then my code works.
var template;
var frag;
If this relates to scope and anyone has the time to explain it would be much appreciated. Ideally I would like to prefix template and frag with the var keyword to increase readability.
I suspect it is the comma between the variable declarations that is breaking your code, and not the use of the
varkeyword per se. Try this:The
varkeyword is already applying to template and frag in the first snippet you have provided, because they are the second and third items in a comma separated list of local variable declarations.The cleanest way to do this is to eschew the syntactic sugar altogether, and separate each variable declaration into a separate statement: