Sammy Ageil

Lead by example

Create an Asynchronous findControl function in WinRT javascript

September 25
by Sammy Ageil 25. September 2012 00:37

In our last tutorial we created a findControl function and used it to return a valid winRT's winControl.
Today we will add the Asynchronous version of our method. Asynchronous operations in javascript's WinRT are handled using javascript Promises or deferreds patterns.
So what is a promise pattern?
A promise or deffered is an object which represents the output of some computation which hasn't necessarily happened or completed yet. When you try to use the value in a promise, the program waits for the computation to complete then returns the computed value to the caller. It is critical to understand that Promises DO NOT create new threads.Promises simply provide a convenient way to do something when something else is done.

Now we understand what is a promise pattern, lets see our Asynchronous findControl and use it.

/// <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 (ctrlId) {
            return document.getElementById(ctrlId).winControl;
        },
        findControlAsync: function (ctrlId) {
            return new WinJS.Promise(function (completed, error) {
                var ctrl = document.getElementById(ctrlId);
                if (ctrl !== undefined && ctrl !== null) {
                    completed(ctrl.winControl);
                }
                else {
                    error();
                }
            });
        }
    });

this script is the exact script from our previous tutorial. The only addition here is the new function declared as findControlAsync. This function uses WinJS.Promise to create our findControlAsync. To call our function we use the following script

MyApplication.Utils.findControlAsync("lView").then(function (ctrol)
        {
		//write to console findControlAsync result is true when the control is found
            console.log("findControlAsync result is = ", ctrol !== null && ctrol !== undefined);
        }, function () { console.error("The specified control was not found in the DOM") });

Note "the lView string parameter is the control id for a winJS listView I have in my default html page"

So what does our call exactly mean?, this call simply calls the findControlAsync, if the call succeeds we use the control to print the specified message otherwise we print a message indicating "the specified control was not found in the DOM".

 

Tags: , ,

javascript | Windows 8 | WinRT

Pingbacks and trackbacks (1)+

Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading