MVVM Examples–Example 2

Concept

Initialization

The binder is responsible for creating and initializing a ViewModel instance. If you want to perform your own initialization in a ViewModel, you can declare your own initial method by annotating a method with @Init . The Binder will invoke this method when initializing a ViewModel. Each ViewModel can only have one initial
method




image
Example3.zul and example3VM.java
<?page title="new page title" contentType="text/html;charset=UTF-8"?>
<zk>
    <window apply="org.zkoss.bind.BindComposer"
        viewModel="@id('myvm') @init('ex.myexample.example3VM')">

        <grid width="400px">
            <rows>
                <row>
                    First Name:
                    <textbox id="fname" value="@load(myvm.firstName)" />
                </row>
                <row>
                    Last Name:
                    <textbox id="lname" value="@load(myvm.lastName)" />
                </row>
            </rows>
        </grid>
        <separator />
        <div align="
                        center ">
            <button id="Submit" label="Submit" />
        </div>
    </window>
</zk>



example3VM.java

package ex.myexample;

import org.zkoss.bind.annotation.Init;

public class example3VM {
    private String firstName;
    private String lastName;
    
    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    @Init
    public void CreatePerson() {
        firstName="john";
        lastName="smith";
    }

}