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.
It is easier to use different views to show the same set of data.
The list box sends the data to the client only if it is visible. It saves a lot of network traffic if the amount of data is huge.
There are three steps to use the live data.
Prepare the data in the form of ListModel. ZK has a concrete implementation called org.zkoss.zul.SimpleListModel. for representing an array of objects.
Implement the org.zkoss.zul.ListitemRenderer interface for rendering an item of data into a list item of the list box.
This is optional. If not specified, the default renderer is used to render the data into the first column.
You could implement different renderers for represent the same data in different views.
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 < 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>
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.