23.01.2018 Views

MICROSOFT_PRESS_EBOOK_PROGRAMMING_WINDOWS_8_APPS_WITH_HTML_CSS_AND_JAVASCRIPT_PDF

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

As a baseline for our discussion, here is a simple renderer:<br />

function simpleRenderer(itemPromise) {<br />

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

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

element.className = "itemTempl";<br />

element.inner<strong>HTML</strong> = "" + item.data.title + "";<br />

return element;<br />

});<br />

}<br />

Again, this structure waits for the item data to become available, and it returns a promise for the<br />

element that will be fulfilled at that time.<br />

A placeholder renderer separates building the element into two stages. The return value is an object<br />

that contains a minimal placeholder in the element property and a renderComplete promise that does<br />

the rest of the work when necessary:<br />

function placeholderRenderer(itemPromise) {<br />

// create a basic template for the item which doesn't depend on the data<br />

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

element.className = "itemTempl";<br />

element.inner<strong>HTML</strong> = "...";<br />

// return the element as the placeholder, and a callback to update it when data is available<br />

return {<br />

element: element,<br />

}<br />

};<br />

// specifies a promise that will be completed when rendering is complete<br />

// itemPromise will complete when the data is available<br />

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

// mutate the element to include the data<br />

element.querySelector(".content").innerText = item.data.title;<br />

element.insertAdjacent<strong>HTML</strong>("afterBegin", "");<br />

})<br />

The element property, in short, defines the item’s shape and is returned immediately from the<br />

renderer. This lets the ListView do its layout, after which it will fulfill the renderComplete promise. You<br />

can see that renderComplete essentially contains the same sort of thing that a simple renderer returns,<br />

minus the already created placeholder elements. (For another example, the added Scenario 8 of the<br />

FlipView example in this chapter’s companion content has commented code that implements this<br />

approach.)<br />

A recycling placeholder renderer now adds awareness of a second parameter called recycled that the<br />

ListView (but not the FlipView) can provide to your rendering function when the ListView’s<br />

loadingBehavior is set to "randomaccess". If recycled is given, you can just clean out the element,<br />

return it as the placeholder, and then fill in the data values within the renderComplete promise as before.<br />

228

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

Saved successfully!

Ooh no, something went wrong!