Alloy Data Binding with ListViews — Part 2 — Showing a No Data Message

Ray Belisle
All Titanium
Published in
2 min readAug 25, 2017

This post is a follow up on Alloy Data Binding with ListViews, please go read that if you haven’t yet.

Alloy data binding is a great feature because you can deliver a lot of functionality with very little code. (I love writing less code!) In order to deliver additional functionality, you do have to write some code. So in this post I am going to provide an approach that uses templates to show a message when ListView has no data. So let’s get started!

In the last post, I showed a simple template that showed an image and a label in the List View. Now we are going to define some extra templates.

Template showing a ‘No Posts’ message

<ItemTemplate name="noDataTemplate" height='80dp'><Label bindId="noData" id="nodata" text="No Posts"></Label></ItemTemplate>

Template with a zero height

<ItemTemplate name="zero" height="0"></ItemTemplate>

With these two new templates, we can now add some code to the controller to handle the showing/hiding of these templates. We pass in the number of records in the Alloy collection, and based on whether there are any records to show, we change the template. If records exist, we apply the zero template, collapsing the row. If there are no records, then we apply the noDataTemplate showing our ‘No Posts’ message.

So, now that we have the templates switching defined, we need to apply it to the correct events. There are 3 events where we need to apply this code.

  1. Initially when we fetch the list view records
  2. Whenever a record is added to the Collection
  3. Whenever a record is deleted from the Collection

The first scenario is simple, we call the updateListView function on the success callback of the collection fetch.

To handle the addition or deletion of records, we hook directly into the backbone events for Collections. You can see the hook into remove and add events.

So, now we’ll put it all together, along with a couple of buttons that let you add and delete records on the fly to see how this works.

--

--