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.

markSupportForProcessing. Note that if you assign a function to an itemTemplate or<br />

groupHeaderTemplate property in JavaScript, it doesn’t need the mark.<br />

In its basic form, a template function receives an item promise as its first argument and returns a<br />

promise whose completed handler creates the elements for that item. Huh? Yeah, that confuses me too!<br />

So let’s look at the basic structure in terms of two functions:<br />

function basicRenderer(itemPromise) {<br />

return itemPromise.then(buildElement);<br />

};<br />

function buildElement (item) {<br />

var result = document.createElement("div");<br />

}<br />

//Build up the item, typically using inner<strong>HTML</strong><br />

return result;<br />

The renderer is the first function above. It simply says, “When itemPromise is fulfilled, meaning the<br />

item is available, call the buildElement function with that item.” By returning the promise from<br />

itemPromise.then (not done, mind you!), we allow the collection control that’s using this renderer to<br />

chain the item promise and the element-building promise together. This is especially helpful when the<br />

item data is coming from a service or other potentially slow feed, and it’s very helpful with incremental<br />

page loading because it allows the control to cancel the promise chain if the page is scrolled away<br />

before those operations complete. In short, it’s a good idea!<br />

Just to show it, here’s how we’d make a renderer directly usable from markup, as in<br />

data-win-options = "{itemTemplate: Renderers.basic }":<br />

WinJS.Namespace.define("Renderers", {<br />

basic: WinJS.Utilities.markSupportedForProcessing(function (itemPromise) {<br />

return itemPromise.then(buildElement);<br />

})<br />

}<br />

It’s also common to just place the contents of a function like buildElement directly within the<br />

renderer itself, resulting in a more concise expression of the exact same structure:<br />

function basicRenderer(itemPromise) {<br />

return itemPromise.then(function (item) {<br />

var result = document.createElement("div");<br />

//Build up the item, typically using inner<strong>HTML</strong><br />

};<br />

})<br />

return result;<br />

208

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

Saved successfully!

Ooh no, something went wrong!