Item template selection logic in JavaScript apps

In this post, we’ll address the mechanics needed to implement item template selection logic in JavaScript apps, which allows for increased flexibility in the way you present your bound data. In C#/C++/VB this would be done with the DataTemplateSelector class, but unfortunately we don’t have that option in JavaScript apps. To illustrate, we’ll start with the Grid App template in JavaScript and will expand its functionality to display multiple item templates.

This is the first post in a series to help address common challenges faced when developing JavaScript based Windows 8 apps. These will be done in collaboration with Arian from Zilverstede, who have several JavaScript apps in the Windows Store.

Expanding the data layer

The first thing we need to do is introduce something in our data model to base our choice for an item template off of. This is where the dynamic nature of JavaScript helps us, as we only need to add a new property to the existing static dataset. Open up the data.js file in the js directory and add a type property to each of the objects in the sampleItems array created on line 83:


Adding a second item template

We’ll need a second template in the groupedItems.html page to use, so let’s replace the default itemtemplate div with the following two divs:

As you may have noticed, we’ve introduced a play class to use, so let’s add the following in the groupedItems.css file (above line 90):

The image is just a simple play icon, which we shift up and down for the hovered state (click on the following thumbnail and save the image in the lightbox):

Play icon

Item template selection logic

Now that we have the data, HTML and CSS in place, we can start implementing the item template selection logic. Open up the groupedItems.js file and add the following method to the page definition (e.g. between the navigateToGroup function declaration on line 12 and the ready declaration on line 18):

What this function does is evaluate the type property we introduced and returns the template according to the item’s type. We can use this function in our ready function instead of the current static reference to the itemtemplate element in our HTML:


Now when we build and run our project, we’ll see that the items with type other than 1 will show the play icon overlay! You can download the complete solution below. If you have any questions, leave me a comment or get in touch on Twitter.


Item template selection sample (384 downloads)
Pin It

3 thoughts on “Item template selection logic in JavaScript apps

  1. Pingback: Windows Store Developer Links – 2013-02-28 | Dan Rigby

  2. Pingback: Rajen's Technical Tidbits Using jQuery in JavaScript apps » Rajen's Technical Tidbits

  3. Pingback: Using jQuery in JavaScript apps

Leave a Reply

Your email address will not be published. Required fields are marked *