23.01.2018 Views

MICROSOFT_PRESS_EBOOK_PROGRAMMING_WINDOWS_8_APPS_WITH_HTML_CSS_AND_JAVASCRIPT_PDF

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

URI scheme, a subject that we’ll be covering later in Chapter 12, “Contracts.” An example of handling<br />

state, in addition to the updates we’ll make to Here My Am! in the next section, can be found in<br />

Scenario 3 of the App model sample.<br />

Basic Session State in Here My Am!<br />

To demonstrate some basic handling of session state, I’ve made a few changes to Here My Am! as given<br />

in the HereMyAm3c example. Here we have two pieces of information we care about: the variables<br />

lastCapture (a StorageFile with the image) and lastPosition (a set of coordinates). We want to make<br />

sure we save these when we get suspended so that we can properly apply those values when the app<br />

gets launched with the previous state of terminated.<br />

With lastPosition, we can just move this into the sessionState object (prepending app.-<br />

sessionState.) as in the completed handler for getGeopositionAsync:<br />

gl.getGeopositionAsync().done(function (position) {<br />

app.sessionState.lastPosition = {<br />

latitude: position.coordinate.latitude,<br />

longitude: position.coordinate.longitude<br />

};<br />

}<br />

updatePosition();<br />

}, function (error) {<br />

console.log("Unable to get location.");<br />

});<br />

Because we’ll need to set the map location from here and from previously saved coordinates, I’ve<br />

moved that bit of code into a separate function that also makes sure a location exists in sessionState:<br />

function updatePosition() {<br />

if (!app.sessionState.lastPosition) {<br />

return;<br />

}<br />

}<br />

callFrameScript(document.frames["map"], "pinLocation",<br />

[app.sessionState.lastPosition.latitude, app.sessionState.lastPosition.longitude]);<br />

Note also that app.sessionState is initialized to an empty object by default, { }, so lastPosition will<br />

be undefined until the geolocation call succeeds. This also works to our advantage when rehydrating<br />

the app. Here’s what the previousExecutionState conditions look like for this:<br />

if (args.detail.previousExecutionState !==<br />

activation.ApplicationExecutionState.terminated) {<br />

//Normal startup: initialize lastPosition through geolocation API<br />

} else {<br />

//WinJS reloads the sessionState object here. So try to pin the map with the saved location<br />

updatePosition();<br />

}<br />

114

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!