Pergunta

I'm trying to figure out how to load the contents of a JavaScript file into a scope. The reason for this is I want to be able to have plug and play capability and be able to load different functionality into my app. Perhaps the user role determines what functionality is loaded, or perhaps I want to tailor my app for a given client.

Here's an example of the contents of one of my pluggable JavaScript file:

myApp.LoginViewModel = (function ()
{
    //DATA
    var self = this;

    return {
        HelloWorld: function ()
        {
            alert('Hellow World from Login View Model');
        }
    };
})();

Here is an example of the configuration file listing what JS files should be loaded:

var myApp = myApp || {};

myApp.ViewModelRegistry =
{
    BaseViewModel: { JavaScriptPath: "/Scripts/ViewModels/BaseViewModel.js"},
    LoginViewModel:{ JavaScriptPath: "/Scripts/ViewModels/LoginViewModel.js"}
};

Here's my code that loops through ViewModelRegistry and uses jQuery to load the script:

    InitializeApp: function ()
    {
        //REGISTER VIEW MODELS
        for (var viewModelName in myApp.ViewModelRegistry)
        {
            var registeredModel = myApp.ViewModelRegistry[viewModelName];

            $.getScript(registeredModel.JavaScriptPath, function (data, textStatus, jqxhr)
            {
            });
        }

        console.log(myApp);
    }
};

My goal is to load the JavaScript function from the JS file into the myApp scope. Each pluggable JS file is scoped to myApp. I thought simply using jQuery's getScript to load the JS file would automatically update the myApp scope since all pluggable JS files are designed to that scope. However, the console.log(myApp) doesn't reveal the code from the JS files. What am I missing? Is this even feasible?

Foi útil?

Solução

I believe your console.log is executed before any of your JS files have been retrieved and parsed. Other than that, you seem to be on the correct course. This is definitely feasible, and the terminology used to describe what you want to achieve is called Asynchronous Module Definitions.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top