Live Data

Like grids[40], list boxes support the live data. With live data, developers could separate the data from the view. In other words, developers needs only to provide the data by implementing the org.zkoss.zul.ListModel interface. Rather than manipulating the list box directly. The benefits are two folds.

There are three steps to use the live data.

  1. Prepare the data in the form of ListModel. ZK has a concrete implementation called org.zkoss.zul.SimpleListModel. for representing an array of objects.

  2. Implement the org.zkoss.zul.ListitemRenderer interface for rendering an item of data into a list item of the list box.

  1. Specify the data in the model property, and, optionally, the renderer in the itemRenderer property.

In the following example, we prepared a list model called strset, assigned it to a list box through the model property. Then, the list box will do the rest.

<window title="Livedata Demo" border="normal"><zscript>String[] data = new String[30];for(int j=0; j &lt; data.length; ++j) {data[j] = "option "+j;}ListModel strset = new SimpleListModel(data);</zscript><listbox width="200px" rows="10" model="${strset}"><listhead><listheader label="Load on demend"/></listhead></listbox></window>                                                                                        

Sorting with Live Data

If you allow users to sort a list box provided with live data, you have to implement an interface, org.zkoss.zul.ListModelExt, in addition to org.zkoss.zul.ListModel.

class MyListModel implements ListModel, ListModelExt {
    public void sort(Comparator cmpr, boolean ascending) {    
        //do the real sorting        
        //notify the listbox (or grid) that data is changed by use of ListDataEvent        
    }    
}

When a user requests the list box to sort, the list box will invoke the sort method of ListModelExt to sort the data. In other words, the sorting is done by the list model, rather than the list box.

After sorted, the list model shall notify the list box by invoking the onChange method of the org.zkoss.zul.event.ListDataListener instances that are registered to the list box (by the addListDataListener method). In most cases, all data are usually changed, so the list model usually sends the following event:

new ListDataEvent(this, ListDataEvent.CONTENTS_CHANGED, -1, -1)

Note: the implementation of ListModel and ListModelExt is independent of the visual presentation. In other words, it can be used with grids, list boxes and any other components supporting ListModel.

In other words, to have the maximal flexibility, you shall not assume the component to used. Rather, use ListDataEvent to communicate with.



[40] The concept is similar to Swing (javax.swing.ListModel).