Creating Global Variables In a Windows 8 Metro JavaScript / HTML5 Application

Posted by Peter Kellner on June 24, 2012 · 3 mins read

The title of this seems ominous and potentially dangerous.  For those that are ready to comment, first think about Globals as Constants, then post away!  The idea is that sometimes you have things in an app that you may want to change system wide.  I just ran into one of those which is the base url of all my services.  To do this, I added to default.js a simple annoymous function that executes.  First, it creates a namespace and assigns the value. It uses WinJS.Namespace.define for this and is as follows:

  app.oncheckpoint = function (args) {
        // TODO: This application is about to be suspended. Save any state
        // that needs to persist across suspensions here. If you need to 
        // complete an asynchronous operation before your application is 
        // suspended, call args.setPromise().
        app.sessionState.history = nav.history;
    };

    WinJS.Namespace.define("AE.Constants", {
        baseUrl: "http://localhost:24008/"
    });

    app.start();

I’ve included the app.oncheckpoint just so you can see where I put this. Now, when I want to use baseUrl, here is all I need:

 

WinJS.xhr({
                type: "post",
                url: AE.Constants.baseUrl +  "EmailDetail/GetEmailByPerson",
                headers: { "Content-type": "application/x-www-form-urlencoded" },
                data: formParams
                
            }).then(function (xhr) {

That’s it!  Hope this helps.