Example 1:
ZK Docs
http://books.zkoss.org/wiki/Small%20Talks/2011/November/Hello%20ZK%20MVVM
In this example, how we can convert MVC GenericForwardComposer into new MVVM + Data binding
ZK Docs
http://books.zkoss.org/wiki/Small%20Talks/2011/November/Hello%20ZK%20MVVM
Step 1:
Create new ZK Project
Step 2:
Create Example1.zul file and its composer as shown
Example1.zul
<window apply="ex.myexample.HelloComposer">
<label id="lbl" />
<button id="btn" label="Show" />
</window>
HelloComposer.Java
package ex.myexample;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.util.GenericForwardComposer;
import org.zkoss.zul.Label;
@SuppressWarnings("rawtypes")
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
Example2.zul
<window apply="org.zkoss.bind.BindComposer" viewModel="@id('myvm') @init('ex.myexample.HelloViewVM')">
<label value="@load(myvm.message)"/>
<button label="Show" onClick="@command('showHello')"/>
</window>
HelloViewVM.Java
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;
}
@Command
@NotifyChange("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. vm.name.
0 comments:
Post a Comment