Sammy Ageil

Disambiguation of Technologies

How to create a winRT javascript helper function

In this tutorial, we will write a static helper function to find an element in the Document Object Model “DOM”. Then return it as a valid a WinRT’s control “winControl”.

Our helper function is called findControl, it will find a winRT control by using it's host's Id

Let's start by looking at our js file;

/// <reference path="//Microsoft.WinJS.1.0/js/base.js" />
/// <reference path="//Microsoft.WinJS.1.0/js/ui.js" />
"use strict";
WinJS.Namespace.define("MyApplication.Utils", {
    findControl: function (elementId) {
        return document.getElementById(elementId).winControl;
    }
});

Now that we have our short and sweet findControl function. Let's try to dissect it to better understand why and how:

  1. What's the deal with all of these reference path comment style entries starting at line 1?
    These lines are not comments, they're references. The sole purpose of their existence is to allow our IDE (Visual Studio.Net) to provide us with its glorious intellisense. You can safely ignore them if you like.
  2. You may say, "Hey this not VB, why do we have strict mode in javascript"?
    The “use strict”; directive is part of ecmascript 5. It can be applied to an entire script file or a function.
    This feature is documented and thoroughly explained in Mozilla References and http://ejohn.org/blog/ecmascript-5-strict-mode-json-and-more/. You should always use this directive, If it causes your code to break, fix the code instead of removing the directive to allow bad code to run.
  3. The next part should be self explanatory, this is how WinRT defines javascript namespaces. While there is nothing to stop you from defining namespace the natural way, this function is the preferred one when using winRT.
  4. Finally, as an detail oriented developer, you have noticed the call to ".winControl" and asked yourself, "What is this?".
    This is a native winRT function; it lives in the winRT ui.js namespace. The function simply uses the winControl property of the host control and return it as a valid winControl.
  5. Code not used and reused is useless code. To call our function, we simply declare a variable and assign it the result of the function call.
var lview = MyApplication.Utils.findControl("listviewCotrol"); //where listViewControl is the ID in the DOM

Of course you will need to reference the script file in your html just like you would do in any web page.

Next time we will add an async function using javascript's promise pattern

Pingbacks and trackbacks (2)+

Comments are closed