Building an Address Book > Creating the Application Functions > The sortListBox() Function

 

The sortListBox() Function

The sortListBox() function alphabetizes (or reverse-alphabetizes) the items in contactListBox_lb. While this operation is potentially complex, the ListBox component makes it easy: ListBox provides a built-in sortItemsBy() method for item sorting. Our sortListBox() function, then, is mostly a convenience wrapper for sortItemsBy().

The sortListBox() function performs the following tasks:

Determines whether to sort in forward or reverse alphabetical order, based on the button through which the function was invoked.

Calls the contactListBox_lb.sortItemsBy() method to sort the contacts in the list.

Because sortListBox() is invoked as a button "click" handler, it automatically receives a reference to the button that triggered it. We store that reference in the component parameter, and use it to determine sort order.

The ListBox's sortItemBy() function expects arguments that govern the result of the sort operation. The first argument specifies whether to sort by "label" or by "data", and the second specifies the sort direction. In our address book, we always sort by item label. We specify "ASC" for an ascending sort (a-z) and "DESC" for a descending sort (z-a) as follows:

  // Ascending sort
  contactListBox_lb.sortItemsBy("label", "ASC");
  
  // Descending sort
  contactListBox_lb.sortItemsBy("label", "DESC");  

The complete listing for sortListBox() is shown below.

/*
 * Function: sortListBox()
 *   Desc: Puts the items in contactListBox into either alphabetical or
 *         reverse alphabetical order.
 *   Parameters:
 *     component    A reference to the component that called the function.
 */

function sortListBox (component) 
{
  // If the A-Z button was pressed...
  if (component == sortAZButton_pb) {
    // ...sort alphabetically.
    contactListBox_lb.sortItemsBy("label", "ASC");
  } else if (component == sortZAButton_pb) {
    // If the Z-A button was pressed, sort in reverse
    // alphabetical order.
    contactListBox_lb.sortItemsBy("label", "DESC");
  }
}