Tuesday, 7 August 2012

MVVM Command annotation and Notify change example

Here is an example, how to pass parameter on a zul through MVVM Command binding annotation.

ZK URL
http://books.zkoss.org/wiki/ZK%20Developer%27s%20Reference/MVVM/Advance/Parameters

Project Structure
image

index.zul

<?page title="Auto Generated index.zul"?>
<window title="Passing argument to MVVM Command" border="normal"
apply="org.zkoss.bind.BindComposer"
viewModel="@id('myvm') @init('domainVMS.TestVM')">
<separator />
<panel width="100%">
<panelchildren>
<separator />
<grid width="99.5%">
<columns>
<column label="" width="150px" />
<column label="" />
</columns>
<rows>
<row>
<hbox>
<label value="Code 1" />
</hbox>
<hbox>
<textbox name="Code1"
value="@bind(myvm.selectedItem.code1)" />
<button label="doSomethid"
onClick="@command('doSomething', codeno='code1')" />
</hbox>
</row>
<row>
<hbox>
<label value="Code 2" />
</hbox>
<hbox>
<textbox name="Code2"
value="@bind(myvm.selectedItem.code2)" />
<button label="doSomethid"
onClick="@command('doSomething', codeno='code2')" />
</hbox>
</row>
<row>
<hbox>
<label value="Code 3" />
</hbox>
<hbox>
<textbox name="Code3"
value="@bind(myvm.selectedItem.code3)" />
<button label="doSomethid"
onClick="@command('doSomething', codeno='code3')" />
</hbox>
</row>
</rows>
</grid>
</panelchildren>
</panel>
</window>

CodeMaster.java

package domainVMS;

public class CodeMaster {

private String code1;
private String code2;
private String code3;

public String getCode1() {
return code1;
}
public void setCode1(String code1) {
this.code1 = code1;
}
public String getCode2() {
return code2;
}
public void setCode2(String code2) {
this.code2 = code2;
}
public String getCode3() {
return code3;
}
public void setCode3(String code3) {
this.code3 = code3;
}


}

TestVM.java


package domainVMS;

import org.zkoss.bind.annotation.BindingParam;
import org.zkoss.bind.annotation.Command;
import org.zkoss.bind.annotation.NotifyChange;
import org.zkoss.zul.Messagebox;

public class TestVM {

private CodeMaster selectedItem = new CodeMaster();


public CodeMaster getSelectedItem() {
return selectedItem;
}


public void setSelectedItem(CodeMaster selectedItem) {
this.selectedItem = selectedItem;
}


@Command
@NotifyChange(".")
public void doSomething(@BindingParam("codeno") String code)
{

if (code.equals("code1"))
{
this.selectedItem.setCode1("aaaaa");
}

if (code.equals("code2"))
{
this.selectedItem.setCode2("bbbb");
}

if (code.equals("code3"))
{
this.selectedItem.setCode3("ccc");
}

}

}

Now you can run the index.zul file and check the output.

1 comment: