My understanding of the WinJS.Application.start() function is that it allows WinJS to queue up certain normal page initialization events to give you a chance to set up other data first in your default.js file. By calling the start() function at the end of default.js, WinJS then fires off all the queued events for you (such as the activated event).
I’m trying to understand where everything fits in the life cycle, so I’m not clear why the first of the following examples works but the second doesn’t. All I’m doing is updating the page title, which doesn’t work as expected when I call app.start() after a 5-second delay:
First, here’s default.html:
<html>
<head>
<script references...>
</head>
<body>
<h1 id="pageTitle">Page of coolness...</h1>
</body>
</html>
And here’s the first default.js example (which works as expected):
(function () {
var app = WinJS.Application;
app.onactivated = function () {
document.getElementById("pageTitle").innerText = "Rock it!";
};
// This code *does* fire the onactivated event:
// The page displays "Rock it!" in the page title
app.start();
})();
Here’s the second default.js example (which doesn’t work as expected):
(function () {
var app = WinJS.Application;
app.onactivated = function () {
document.getElementById("pageTitle").innerText = "Rock it!";
};
// This code *doesn't* fire the onactivated event:
// It initially displays "Page of coolness..." in the page title.
// After 5 seconds, it adds "Gettin' there...Almost made it..."
// to the the page title, but "Rock it!" never gets displayed
WinJS.Promise.timeout(5000).then(function () {
document.getElementById("pageTitle").innerText += "Gettin' there...";
app.start();
document.getElementById("pageTitle").innerText += "Almost made it...";
});
})();
Why does calling app.start() after the 5-second delay cause the activated event not to fire?
The documentation for the
startfunction is a little misleading.When you call
start,WinJS.Applicationbegins to queue and dispatch events, including those which are emitted byWindows.UI.WebUI.WebUIApplication. One of these events isactivated, which is what leads to your handler function being called.The important point is that the queuing doesn’t begin until you call
start. Any events that are emitted byWebUIApplicationbefore the queuing begins are lost forever.This is the situation you have created by delaying your call to
start: theactivatedevent is sent byWebUIApplicationbefore theWinJS.Applicationqueue has been set up. Theactivatedevent is never received byWinJS.Applicationand so your handler function is never invoked.I know you are just trying to figure out the life cycle, but there isn’t a reason to delay your call to the
startfunction in real life. The only way to get the effect you are trying to create in your code is to place the Promise inside theonactivatedhandler function, like this: