In this tutorial we will write a static helper function to find an element in the Document Object Model “DOM” and return it as a valid a WinRT’s control “winControl”.
Our helper function is called findControl, it will find a winRT control by using its 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;
}
});
The first thing you will notice in our script is the presence of these reference path comments look a like.
/// <reference path="//Microsoft.WinJS.1.0/js/base.js" />. These lines are not comments, they references and they only exists so Visual Studio.Net to provide us with its glorious intellisense. you can safely ignore them if you like.
The second new part is more interesting, our script file includes a “use strict”; directive, what is this use strict you say?
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/
The third part is the new way of defining a javascript namespace this is functionality only exists in WinRT. While there is nothing to stop you from defining namespace the natural way, this function is the preferred one when using winRT.
The last new part you will notice is the “.winControl”, this part a native function of the winRT ui.js.
The function simply uses the winControl property of the host control and return it as a valid winControl
Finally to use our function we need to call it like this
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
Hope this helps