Getting Started With Metro JavaScript
Getting Started With Metro JavaScript
Written by Ian Elliot   
Wednesday, 11 April 2012
Article Index
Getting Started With Metro JavaScript
Hello World
Private Variables

Private Variables - Closure



Although this is a simple introduction to Metro JavaScript, it is worth pointing out at least one slightly more advanced feature of the basic situation. The documentation encourages you to define a lot of your code within immediate functions because it has lots of advantages.

For example, there is an additional advantage of defining your functions within an immediate function courtesy of closure you can make use of private variables.

It has to be admitted that many JavaScript programmers don't inderstand closure and if you are hazy on the idea then look it up. The simple explanation of closure is that any variable that is defined at the same time as a function continues to be available and accessible to that function even if the variable should have been destroyed. This sounds magical and is the reason many JavaScript programmers just don't believe it works - but it does.

For example, lets define the button click event handler within the immediate function using:

var message = "Hello World From A Private Variable";
function () {
var Button1 =
Button1.textContent = message;

This is a common idiom in more advanced JavaScript - you can define a function right were it is being used. In this case notice the new variable message. This is defined within the immediate function and so it is destroyed before the event handler is ever called. And yet the event handler can still make use of it because of closure. The event handler function still exists long after the immediate function has terminated and it stores all of the variables that were declared at the same time it was. This is what closure is all about. Notice that functions that weren't defined within the immediate function don't have access to message and it isn't a global variable.

Don't worry if you don't quite follow this as you will use it so often that it will become second nature very soon.

A Small Example

After Hello World one of the most common example programs is to bounce a ball around an area of the screen. If you don't know how to do this sort of thing in HTML and JavaScript take a look at:JavaScript Pong which is a much more sophisticated example of the technique.

Start a new blank JavaScript application. The ball that we are going to bounce around could just be a simple div but we might as well use the storelogo.png image provided by the template. This is the star that appears in the start screen as your application's logo.

So all we need to do is create a DOM img object, load the file into it and set some properties so that we can position the image:

var ball = document.createElement("img");
ball.src = "..\\images\\storelogo.png"; = "absolute"; = "1px"; = "1px";

The image of the star is stored in the images subdirectory within the project. We set the images position property to absolute so that we can set its exact position.

All of this code goes into the immediate function after the second if statement - i.e. where your app's initialization code always goes. In a bigger program we would move much of this code out to separate functions but for simplicity let's just code it all in one place.

Next we need to setup a timer interrupt and this is done in the usual way with setInterval:

  var vx = 1;
var vy = 1;

setInterval(function () {
var py = parseInt(;
var px = parseInt(;
if (px>100 | px<1) {vx=-vx};
if (py>150 | py<1) {vy=-vy}; =py+vy  +"px"; = px+ vx + "px";
, 10);

Notice that vx and vy are private variables for the function defined within setInterval because of the operation of closure. Also notice that we are using the idiom of defining the ball's update function where it is being used, rather than somewhere else in the file. The update simply gets the current position of the image and checks to see it it is on the edge of the display area. if it is then the "velocities" are reversed to make it appear to bounce. Then the velocities are used to update the position. The timer interval is set to 10 milliseconds.

If you put all this in and run the program you will see the star image bounce around the screen. This isn't a high quality animation but you should be able to see the principle. In many ways the purpose of the example is to give you confidence that you really are working with HTML5 and JavaScript and not some strange new environment.

We also haven't provided any way of stopping the bouncing ball and we haven't dealt with the lifecycle management that would be needed to keep everything working correctly. 



You could easily add a set of walls for the ball to bounce off and sound. In fact it would be quite easy to port the JavaScript pong program referenced earlier but there are so many better ways of creating an animation using HTML5 and JavaScript that it would be better to wait to see more of the what is to come in subsequent chapters.

What is different?

Using the above approach you can simply code your JavaScript app as if it was hosted by a web page.

Some things won't work, however.

For example, you can't use alert() to pop up an alert box because Metro apps are full screen single windowed. There are alternatives but these are specific to WinJS.

If you want to take advantage of the extra features then there are a number of things that you have to master. In particular, you need to know about the WinJS controls that are provided and how to work with them using databinding.

You also need to be aware of the application's life cycle and how to use the promise object to work asynchronously. Finally you need to master both tile and toast notifications.

All of these topics are covered in the subsequent chapters.


  • The two important files in your project are default.html and default.js which hold the HTML and JavaScript for your application.
  • The basic structure of your program is an immediate function which sets up two event handlers to deal with the life cycle of a typcial app - this is where your initialization code goes.
  • The use of an immediate function ensures that any variables you declare within it are not global and destroyed as soon as the function terminates.
  • Use addEventListener to set up even handlers
  • Any functions that you define within the immediate function have access to any variables you declare due to the action of closure - this is a way of giving functions private variables.

You can download the code for the program snippets in this chapter in a single ZIP file from the CodeBin.
(Note you have to register first)


To read more of this book click its cover image:












or email your comment to:


To be informed about new articles on I Programmer, subscribe to the RSS feed, follow us on Google+, Twitter, Linkedin or Facebook or sign up for our weekly newsletter.

Last Updated ( Wednesday, 29 August 2012 )

Copyright © 2018 All Rights Reserved.
Joomla! is Free Software released under the GNU/GPL License.