Skip to content

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

Updated: at 05:05 PM

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(<span class="str">&quot;AE.Constants&quot;</span>, {
    baseUrl: <span class="str">&quot;http://localhost:24008/&quot;</span>
});

app.start();</pre>

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(<span class="kwrd">function</span> (xhr) {</pre>

That’s it!  Hope this helps.