HTML and CSS Reference
In-Depth Information
Applying the Template to the App
Before you use a template, you must ensure that the
WinJS.UI.processAll
method has been
called. This method processes the HTML document, looking for elements that have the
data-
win-control
attribute and configuring their capabilities. This includes finding and processing
templates.
Listing 2-14 shows the changes to the
performInitialSetup
function defined in the
default.js
file where I added the call to the
displayListItems
and
setupListEvents
func-
tions after the call to
WinJS.UI.processAll
(and where I removed the code for the previous
example from the
performInitialSetup
function).
Listing 2-14.
Ensuring That Elements Are Processed Before Using a Template
…
function performInitialSetup(e) {
WinJS.UI.processAll().then(function () {
UI.List.displayListItems();
UI.List.setupListEvents();
});
}
…
he
processAll
method does its work in the background, allowing the JavaScript state-
ments that follow a call to
processAll
to be executed at the same time. Using background tasks
is a good idea, but since my
displayListItems
function relies on the
winControl
property that
is created by
processAll
, I need to make sure that the background task has been completed
before I use my template.
Understanding Promises
Metro apps rely on the JavaScript
Promise
pattern to represent background tasks. The result
from the
processAll
method is a
WinJS.Promise
object, which is the Metro implementation of
the JavaScript Promise pattern.
To use the
Promise
object, I call the
then
method on the object, passing in a function that
will be executed when the task has completed. In my example, this function makes the calls to
the
UI.List
namespace that depend on the
processAll
method having completed its work.
he
then
method takes optional second and third arguments that define functions that will
be executed if there is an error and that will receive process information, but for this topic I just
assume that all background tasks complete properly. I recommend you take the time to handle
any errors properly in your own projects.
■
This is the most basic and common use of a JavaScript promise. Take a look at the API
definition for the
WinJS.Promise
object to learn about the other capabilities available. Be careful,
though; JavaScript promises are a simplified representation of some complex parallel program-
ming concepts, and you can get into a lot of trouble using them if you are not careful. Part of
the problem is that JavaScript supports background tasks but doesn't provide the mechanisms
Tip
Search WWH ::

Custom Search