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.

Note that the productListings collection is an IMapView object and not an array; you can retrieve a<br />

specific item in the collection by using its lookup method, as in the code above, or by using a key-based<br />

array lookup:<br />

var product1 = listing.productListings["product1"];<br />

Iterating through the IMapView takes a little more work; it does not support index-based lookup nor<br />

the foreach method. You instead use an IIterator obtained through the first method, as shown<br />

here:<br />

var iterator = listing.productListings.first()<br />

var product;<br />

while (iterator.hasCurrent) {<br />

product = iterator.current.value;<br />

document.getElementById(product.productId + "SellMessage").innerText =<br />

"You can buy " + product.name + " for: " + product.formattedPrice + ".";<br />

iterator.moveNext();<br />

};<br />

This code is completely equivalent to the previous snippet and relies on the fact that the product ID<br />

just so happens to match the first part of the appropriate element ID in the <strong>HTML</strong>. In any case, this is the<br />

sort of code you would use to present a variable list of options to the user.<br />

In doing so, you’ll likely want to filter out those products that have already been purchased. In that<br />

case, you’d look up the product license within the CurrentApp.licenseInformation.productLicenses<br />

collection, which is another IMapView of ProductLicense objects, using the product’s ID as the key.<br />

Here’s how we’d modify the code above to perform this additional step:<br />

var iterator = listing.productListings.first()<br />

var licenses = currentApp.licenseInformation.productLicenses;<br />

var product, message;<br />

while (iterator.hasCurrent) {<br />

product = iterator.current.value;<br />

if (licenses[product.productId].isActive) {<br />

message = "You own " + product.name + ".";<br />

} else {<br />

message = "You can buy " + product.name + " for: " + product.formattedPrice + ".";<br />

}<br />

};<br />

document.getElementById(product.productId + "SellMessage").innerText = message;<br />

iterator.moveNext();<br />

If you use this code in Scenario 2 of the sample (which is provided in the modified sample in this<br />

chapter’s companion content), you’ll see the message “You own Product 1” when you first switch to that<br />

scenario. You could also add a further refinement to check the expirationDate property of each<br />

product license and display its remaining time.<br />

778

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

Saved successfully!

Ooh no, something went wrong!