次の方法で共有


Data Binding: Windows 8 Store App using JavaScript

As the amount of data organisations store explodes we need easier more intuitive ways to navigate the mass of data. The IMDb claims to have over 2 million titles in their database and Wikipedia has a lot of films listed. So I think we are all good for a large enough dataset for our sample app.

Lets start by creating a new project using the Navigation App template.

First:

image

Then:

image

 

For simplicity we are going to start off with a hard coded dataset with just a few fields so its easier to follow. First we need to add a JavaScript file that contains our data, lets add it to the js folder:

image

 

Here is the hardcoded data we are going to use:

(release dates are not accurate)

The final file should look like this:

Displaying the data using standard old school web techniques is straight forward. Add a HTML container then some JavaScript to insert new elements into the container.

The container is a simple unordered list:

  1. <ul id=”movieList”>
  2. </ul>

The JavaScript is also straight forward:

Browse the complete code here.

This is great but we would like to take advantage of data binding. This should reduce the amount of JavaScript that we have to write and maintain as well as update the UI when the data changes.

Upgrading to Data Binding

We are going to take advantage of the helper functions in WinJS.Binding and the ListView in WinJS.UI to easily display our data.

First we need to add a HTML template in home.tml that defines how each of our movie titles should be rendered. This is very similar to other JavaScript frameworks like knockout.js and backbone.js.

Take note of the id for the WinJS template, movieListTemplate, as we will be using it in the ListView control.

Then we change our ordered list, in home.html, to the WinJS ListView control:

Line three has quite a lot going on. The data source used in line 3 still needs to be created its as simple as adding the following to data.js:

  1. var moviesList = new WinJS.Binding.List(moviesArray);

Also in line three is the special syntax that can be used to declaratively select a template to use with the control

  1. itemTemplate: select('#movieListTemplate')

You may have noticed that the HTML contains a bunch of data-win-* attributes. This is how the rendering engine knows which tag and object to use. The magic happens when you call WinJS.UI.processAll() in the home.js file. All the HTML binding code can be replaced with JavaScript, if that's how you roll.

The complete code of this change can be viewed here.

More posts in this series to follow.