Saturday, 2 June 2012

MVVM Examples–Example 1

Example 1:
In this example, how we can convert MVC GenericForwardComposer into new MVVM + Data binding

ZK Docs

Step 1:

Create new ZK Project

Step 2:

Create Example1.zul file and its composer as shown
<window apply="ex.myexample.HelloComposer">
    <label id="lbl" />
    <button id="btn" label="Show" />

package ex.myexample;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.util.GenericForwardComposer;
import org.zkoss.zul.Label;

public class HelloComposer extends GenericForwardComposer {
    private static final long serialVersionUID = -6397566602389346161L;
    private Label lbl;

    public void onClick$btn(Event event) {
        lbl.setValue("Hello World!");

Step 3:

Run the Example1.zul file

Step 4:

Let us re write the same example using MVVM
Create Example2.zul and HelloViewVM.Java as shown
<window apply="org.zkoss.bind.BindComposer" viewModel="@id('myvm') @init('ex.myexample.HelloViewVM')">
    <label value="@load(myvm.message)"/>
    <button label="Show" onClick="@command('showHello')"/>
package ex.myexample;
import org.zkoss.bind.annotation.Command;
import org.zkoss.bind.annotation.NotifyChange;

public class HelloViewVM {
    private String message;

    public String getMessage() {
        return message;

    public void showHello() {
        message = "Hello World!";

Reference a ViewModel in a ZUL
We can bind ZK UI component to a ViewModel by setting its viewModel attribute, and that component becomes the Root View Component for the ViewModel. All child components of this Root View Component can acces the same ViewModel and its properties. To bind a ViewModel, we have to apply a composer called org.zkoss.bind.BindComposer, it will create a binder for the ViewModel and instantiate the ViewModel's class.
Then we set viewModel attribute with ViewModel's id in @id ZK Bind annotation and a ViewModel's full-qualified class name in @init . We use the id to reference ViewModel's properties, e.g.

No comments:

Post a Comment