Extending WinJS ListView With Custom Item Events

Introduction

This article demonstrates how to extend a WinJS ListView control with custom item events like onItemsloading, onItemsLoaded, onItemFocus, onItemBlur etcetera. In the end, it gives you an idea of how to extend a WinJs control with custom events indirectly.

In this article, I'll discuss how to add the following events to a WinJS ListView control and listen with your custom code.

Event

Description

onItemsLoaded         

Fired when all the list items loaded in ListView

onItemsLoading

Fired when items loading in ListView

onViewPortLoaded

Fired when items view port loaded

onFocus

Fired when item receives focus

onBlur

Fired when item lost focus


Creating a blank JavaScript store app

Create a blank JavaScript store app with the name say "ExtendListViewApp".

NewApp.png
 

Add a new JavaScript file for data initialization.

Add a new Java Script file data.js (or grab it from the attached zip). This file is responsible for creating a list with countries and storing it in the global namespace with the name MyData.

ListViewData.png
 

Adding ListViewExtension JavaScript file

Grab ListViewExtension.js from attached source code. This file is responsible for extending ListView control with custom item events.

In three steps, you can attach a custom event to any control, they are:

1. Define control custom event constants (to be consistent across the app instead of hard-coding the string values) but not essential.

ListViewEventConstants.png

 2. Clone the original method with a new name and attach it to the control.  Create a new method with the original method name and add your custom code. Don't forget to call the original method. 

 ListViewHook.png

 3) Register custom events. This can be done by calling WinJS.Class.mix

ListViewEventMix.png

Adding a ListView control

Open default.html, add a  ListView control with item template as shown in the following (or copy the code from default.html in the attached source code). Here an extra textarea is included for event output logging from event listeners. 

ListViewControl.png
 

Adding Event listeners

Add a new JavaScript file, say MyList.js, then add the following code in the page ready event:

ListViewEvents.png 

You can access the WinJS control from obj.target.

The Log function looks as in the following:

ListViewLog.png
 

Adding script references

Open default.html and add the script references; ListViewExtensions.js must be after ui.js and before MyList.js; see:

ScriptsOrder.png
 

All done, deploy and run the app. Click items one by one, the item focus and blur events are fired. All the log messages will appear in the textarea.

Output

Output.png
 

Summary

In this article, I discussed how to extend a WinJS control with custom events.

The source code is attached.

Up Next
    Ebook Download
    View all
    Learn
    View all