This example is borrowed from Backbone directory demo app
https://github.com/ccoenraets/backbone-directory/blob/master/web/js/utils.js#L11
// The Template Loader. Used to asynchronously load templates located in separate .html files
window.templateLoader = {
load: function(views, callback) {
var deferreds = [];
$.each(views, function(index, view) {
if (window[view]) {
deferreds.push($.get('tpl/' + view + '.html', function(data) {
window[view].prototype.template = _.template(data);
}, 'html'));
} else {
alert(view + " not found");
}
});
$.when.apply(null, deferreds).done(callback);
}
};
You initialize this with array of strings [views] and [callback] function.
My question is how window[view] (click above link to exact position in the code) can be checked if (as far as I see) wasn’t be initialized previously? If I’m not precise please write this in comments.
If I’ve understood your question correctly, then when you call
templateLoader.loadyou pass in 2 arguments;viewsandcallback. We can assume thatviewsis an array, since we then iterate over that array with the jQuery.each()method. The callback to.each()is passed the element of theviewsarray that corresponds to the current iteration. That argument is namedview.So
viewis some arbitrary value that was stored in theviewsarray. We then try to find a property ofwindowwith the identifier that matches the value ofview. Ifview === "james"we are looking forwindow.james.If you look at some of the views in that app you will see that they are defined like this:
So
ContactViewis a property ofwindow, and we could calltemplateLoader.loadlike the following to load that template:And you can see where that actually gets called in main.js.
So what’s actually happening is a bunch of properties of
windoware defined in various other files, and then loaded by the template loader, by passing an array of identifiers to it.