Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you reference to javascript window element before initianization?

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.

like image 329
sobi3ch Avatar asked Sep 20 '26 04:09

sobi3ch


1 Answers

If I've understood your question correctly, then when you call templateLoader.load you pass in 2 arguments; views and callback. We can assume that views is an array, since we then iterate over that array with the jQuery .each() method. The callback to .each() is passed the element of the views array that corresponds to the current iteration. That argument is named view.

So view is some arbitrary value that was stored in the views array. We then try to find a property of window with the identifier that matches the value of view. If view === "james" we are looking for window.james.

If you look at some of the views in that app you will see that they are defined like this:

window.ContactView = Backbone.View.extend({
    // Some methods
});

So ContactView is a property of window, and we could call templateLoader.load like the following to load that template:

templateLoader.load(["ContactView"], someCallbackFn);

And you can see where that actually gets called in main.js.

So what's actually happening is a bunch of properties of window are defined in various other files, and then loaded by the template loader, by passing an array of identifiers to it.

like image 67
James Allardice Avatar answered Sep 24 '26 16:09

James Allardice