Get ZK Up and Running with MVVM"

From Documentation
 
(52 intermediate revisions by 5 users not shown)
Line 1: Line 1:
{{Template:UnderConstruction}}
 
 
 
= Introduction =
 
= Introduction =
 
<!--
 
<!--
Line 8: Line 6:
  
  
This tutorial is intended for software developers who have experience in writing Java program. We will guide you how to build a modern web application with ZK. The target application we are going to build is a simple car catalog application. We have introduced '''MVC''' approach in previous Tutorial<ref> [[Tutorial]]</ref>. If you have read it, you could skip first several chapters and jump to [[#Automatic UI Controlling| Automatic UI Controlling]]. In this article, we will present another approach which is classified to '''Model-View-ViewModel (MVVM)''' design pattern. Using this approach, ZK can control components for you automatically.
+
This tutorial is intended for software developers who have experience in writing Java EE programs. We will guide you on how to build a modern web application with ZK. The target application we are going to build is a simple car catalog application. In this article, we will present an approach that is classified as the '''Model-View-ViewModel (MVVM)''' design pattern. Using this approach, ZK can control components for you automatically and it separates the UI from its controller clearly. In addition, you can also choose to go with the <b>MVC</b> approach that is covered in another tutorial <ref> [[ZK Getting Started/Get ZK Up and Running with MVC]]</ref>.
 
 
You can take look at [http:// target application's live demo]. We also provide the complete source code with an Eclipse project zip file in [[#Download| Download]] section.
 
  
 +
<!--
 +
You can see the example application deployed on-line here [http:// target application's live demo].
 +
-->
  
  
  
 
{{Template:tutorial common chapters}}
 
{{Template:tutorial common chapters}}
 
 
 
 
=Sketch User Interface =
 
 
Design UI is a good step to start building an application, since it helps you define the scope of your application. ZK provides hundreds of ready-made UI components. Developers can rapidly build their desired user interface by combining these components without creating from scratch.
 
 
In ZK, you can use ZK User Interface Markup Language (ZUML) <ref> [[ZUML Reference|ZUML Reference]] </ref>, an XML-formatted language, to describe user interface. In ZK default convention, the files to describe user interface use '''.zul''' as file name suffix. One component can be represented as an XML element (tag), and you can configure each component's style, behavior, and function by setting XML element's attributes.<ref> [[ZK Component Reference|ZK Component Reference]] </ref>
 
 
First of all, we use a ''window'' with specified title and normal border as our application's frame.
 
 
 
'''Extracted from search.zul'''
 
<source lang="xml">
 
 
<window title="Search Product" width="600px" border="normal">
 
<!-- put child components inside a tag's body -->
 
</window>
 
</source>
 
 
As ''window'' is the outmost component, it's called the ''root component''. ''Window'' is a mostly common used container because it's a basic display element of a desktop-like application and it can also encloses other components. All other components inside the ''window'' should be put in window tag's body, and they are called ''child component''. We set ''window'''s title bar text with "title" attribute and make ''window'' display a normal border with "border" attribute. For "width" attribute, use CSS like syntax such as "800px" or "60%".
 
 
 
Basically, our example application's user interface is divided into 3 areas inside a ''window'', they are (from top to bottom) search function, car list, and car details area.
 
 
[[File:Tutorial-ui-3areas.png |400px| center]]
 
 
 
'''Search Area.'''
 
ZK components are like building blocks, you can combine existing components to construct your desired user interface. To allow users to search, we need a text to tell user what they should input, a place to enter keywords, and a button for triggering search. We can use following ZK components to fulfill this requirement:
 
 
'''Extracted from searchMvvm.zul'''
 
<source lang="xml">
 
 
<hbox align="center">
 
Keyword:
 
<textbox />
 
<button label="Search" image="/img/search.png" />
 
</hbox>
 
 
</source>
 
 
The ''hbox'' ("h" means horizontal) is a layout component and it can arrange its child components in horizontal order. Because these three child components have different height, we use "align" attribute to arrange them for elegance. You can easily create an image button by specifying path at "image" attribute.
 
 
 
'''Car List Area.''' ZK provides several components to display a collection of data such as ''listbox'', ''grid'', and ''tree''. We use ''listbox'' to display a list of car with 3 columns: Name, Company and Price. We set "height" attribute to limit fixed number of visible row and you can drag scroll-bar to see the rest of rows. The "emptyMessage" attribute is used to show a message when ''listbox'' contains no items. The ''listbox'' is a container component, and you can add ''listhead'' to define a column. The ''listitem'' is used to display data, and the number of ''listcell'' in one ''listitem'' should equals to the number of ''listheader''. Here we use ''listcell'' with static value to demonstrate structure of a ''listitem'', and these will be replaced in next chapter.
 
 
'''Extracted from searchMvvm.zul'''
 
<source lang="xml">
 
<listbox height="160px" emptyMessage="No car found in the result">
 
<listhead>
 
<listheader label="Name" />
 
<listheader label="Company" />
 
<listheader label="Price" width="20%"/>
 
</listhead>
 
<listitem>
 
<listcell value="product name"></listcell>
 
<listcell value="company"></listcell>
 
<listcell>$<label value="price" /></listcell>
 
</listitem>
 
</listbox>
 
</source>
 
 
 
 
 
'''Car Details Area.''' Like the ''hbox'', ''vbox'' is also a layout component which arranges its child component in vertical order. By combing these 2 layout components, we can present more information on a screen.  The "style" attribute allows you to customize component's style with CSS syntax.
 
 
'''Extracted from searchMvvm.zul'''
 
<source lang="xml">
 
<hbox style="margin-top:20px">
 
<image width="250px" />
 
<vbox>
 
<label />
 
<label />
 
<label />
 
<label />
 
</vbox>
 
</hbox>
 
</source>
 
 
 
You can see complete zul through the link in References section. <ref> [http://code.google.com/p/zkbooks/source/browse/trunk/tutorial/WebContent/searchMvvm.zul searchMvvm.zul] </ref>
 
  
 
= Automatic UI Controlling =
 
= Automatic UI Controlling =
Line 110: Line 25:
 
The approach we introduce here to control user interaction is to '''let ZK control UI components for you'''. This approach is classified to '''Model-View-ViewModel''' ('''MVVM''') design pattern. <ref> [[ZK Developer's Reference/MVVM| MVVM in Developer's Reference]] </ref> This pattern divides an application into three parts.
 
The approach we introduce here to control user interaction is to '''let ZK control UI components for you'''. This approach is classified to '''Model-View-ViewModel''' ('''MVVM''') design pattern. <ref> [[ZK Developer's Reference/MVVM| MVVM in Developer's Reference]] </ref> This pattern divides an application into three parts.
  
The '''Model''' consists of application data and business rules. <tt>CarService</tt> and other classes used by it represent this part in our example application.
+
The '''Model''' consists of application data and business rules. <code>CarService</code> and other classes used by it represent this part in our example application.
  
The '''View''' means user interface. The zul page which contains ZK components represents this part. An user's interaction with components triggers events to be sent to controllers.
+
The '''View''' means user interface. The zul page which contains ZK components represents this part. A user's interaction with components triggers events to be sent to controllers.
  
 
The '''ViewModel''' is responsible for exposing data from the Model to the View and providing required action requested from the View. The ViewModel is type of '''View abstraction''' which contains a View's state and behavior. But '''ViewModel should contain no reference to UI components'''. ZK framework handles communication and state synchronization between View and ViewModel.
 
The '''ViewModel''' is responsible for exposing data from the Model to the View and providing required action requested from the View. The ViewModel is type of '''View abstraction''' which contains a View's state and behavior. But '''ViewModel should contain no reference to UI components'''. ZK framework handles communication and state synchronization between View and ViewModel.
  
Under this approach, you just '''prepare a ViewModel class''' with proper setter, getter and behavior methods. Then '''specify data binding expression on component's attributes''' in a ZUL. There is a binder in ZK which will synchronize data between ViewModel and components and handle events automatically according to your binding expression. You don't need to control components by yourself.
+
Under this approach, we just '''prepare a ViewModel class''' with proper setter, getter and application logic methods, then '''assign data-binding expression to a component's attributes''' in a ZUL. There is a binder in ZK which will synchronize data between ViewModel and components and handle events automatically according to binding expressions. We don't need to control components by ourselves.
  
  
Here we use search function to explain how MVVM works in ZK. Assume that a user click "Search" button then ''listbox'' updates its content. The flow is as follows:
+
Here we use the search function to explain how MVVM works in ZK. Assume that a user click "Search" button then ''listbox'' updates its content. The flow is as follows:
  
 
[[Image:tutorial-mvvm.png | center]]
 
[[Image:tutorial-mvvm.png | center]]
Line 137: Line 52:
 
-->
 
-->
  
== Abstract the View==
+
== Abstracting the View==
  
 
<!--
 
<!--
Implement ViewModel concept with a class
+
Implement the ViewModel concept with a class
 
usage of Java annotation for data binding
 
usage of Java annotation for data binding
 
-->
 
-->
ViewModel is an abstraction of View. Therefore when we design a ViewModel, we should analysis UI's functions for what '''state''' it contains and what '''behavior''' it has.
+
ViewModel is an abstraction of View. Therefore when we design a ViewModel, we should analyze UI's functions for what ''' state''' it contains and what '''behavior''' it has.
  
 
The state:
 
The state:
Line 150: Line 65:
 
# selected car
 
# selected car
  
The behavior:
+
The operation:
 
# search
 
# search
  
  
According to above analysis, the ViewModel should have 3 variables for above states and one method for the behavior. In ZK, creating a ViewModel is like creating a POJO, and it exposes its states like JavaBean's properties through setter and getter methods.  The search method implements search logic with service class and updates property "carList".
+
According to the above analysis, the ViewModel should have 3 variables for the above states and one method for the behavior. In ZK, creating a ViewModel is like creating a POJO, and it exposes its states like JavaBean's properties through setter and getter methods.  The search method implements search logic with service class and updates the property "carList".
  
 
'''SearchViewModel.java'''
 
'''SearchViewModel.java'''
<source lang="java">
+
<syntaxhighlight line lang="java">
 
package tutorial;
 
package tutorial;
  
Line 176: Line 91:
 
}
 
}
  
</source>
+
</syntaxhighlight>
  
  
 
'''Annotation'''
 
'''Annotation'''
  
In ZK MVVM, any behavior which can be requested by a View is a '''command''' in a ViewModel. Then you can bind a component's event to the command and ZK will invoke the method when bound event is triggered. In order to let ZK knows which behavior (method) can be requested, you should apply an annotation <tt>@Command</tt> on a method. We mark <tt>search()</tt> as a "command" with '''default command name''', search, which is the same as method name. The command name is used in data binding expression we'll talk about in next section.
+
In ZK MVVM, any behavior that a View can request is a '''command''' in a ViewModel. We can bind a component's event to the command and ZK will invoke the method when a bound event is triggered. In order to let ZK know which behavior (method) can be requested, you should apply an annotation <code>@Command</code> on a method. We mark <code>search()</code> as a "command" with '''default command name''', search, which is the same as method name. The command name is used in the data-binding expression we'll talk about in the next section.
  
  
In <tt>search()</tt>, we change a ViewModel's property: <tt>carList</tt>. Thus, we should tell ZK this change with <tt>@NotifyChange</tt> so that ZK can reload the changed property for us after it invokes this method.
+
In <code>search()</code>, we change a ViewModel's property: <code>carList</code>. Thus, we should tell ZK this change with <code>@NotifyChange</code> so that ZK can reload the changed property for us after it invokes this method.
  
For "search" command, it looks like:
+
For the "search" command, it looks like this:
  
 
'''SearchViewModel.java'''
 
'''SearchViewModel.java'''
<source lang="java" high="10,11">
+
<syntaxhighlight line lang="java" highlight="10,11">
 
package tutorial;
 
package tutorial;
  
Line 205: Line 120:
 
}
 
}
 
}
 
}
</source>
+
</syntaxhighlight>
  
  
For complete source code, please refer to References section. <ref>  [http://code.google.com/p/zkbooks/source/browse/trunk/tutorial/src/tutorial/SearchViewModel.java SearchViewModel.java] </ref>
+
For complete source code, please refer to [https://github.com/zkoss-demo/gettingStarted/blob/master/src/main/java/tutorial/SearchViewModel.java Github]
  
== Bind UI to ViewModel ==
+
== Binding UI to ViewModel ==
In MVVM approach, the way to sketch UI is the same as MVC approach. Then you specify relationship between a ZUL and a ViewModel by writing data binding expression in component's attribute, and let ZK handles components for you.
+
Under MVVM, we build our UI as same as we would with the MVC approach, then we specify the relationship between a ZUL and a ViewModel by writing data binding expression in component's attribute and let ZK handle components for us.
  
To bind a component to a ViewModel, you should apply a composer called '''org.zkoss.bind.BindComposer'''. This composer processes data binding expressions and initializes the ViewModel's class. Then we can bind this component to a ViewModel by setting its '''viewModel''' attribute with following syntax:
+
=== Bind a ViewModel ===
 +
To bind a component to a ViewModel, we should apply a composer called '''org.zkoss.bind.BindComposer'''. This composer processes data binding expressions and initializes the ViewModel class. We then bind this component to a ViewModel by setting its '''viewModel''' attribute with following syntax:
  
'''<tt>@id('ID') @init('FULL.QUALIFIED.CLASSNAME')</tt>'''
+
'''<code>@id('ID') @init('FULL.QUALIFIED.CLASSNAME')</code>'''
  
* <tt> @id() </tt> is used to set ViewModel's id to whatever you want like a variable name. You will use this id to reference ViewModel's properties (e.g. vm.carList) in a data binding expression.
+
* <code> @id() </code> is used to set ViewModel's id to whatever we want like a variable name. We will use this id to reference ViewModel's properties (e.g. vm.carList) in a data binding expression.
* You should provide full-qualified class name for <tt> init()</tt> to initialize the ViewModel object.
+
* We should provide full-qualified class name for <code>@init()</code> to initialize the ViewModel object.
  
  
'''searchMvvm.zul'''
+
'''Extracted from searchMvvm.zul'''
<source lang="xml" high="2">
+
<syntaxhighlight line lang="xml" highlight="2">
<window title="Search Product" width="600px" border="normal"  
+
<window title="Search" width="600px" border="normal"  
apply="org.zkoss.bind.BindComposer" viewModel="@id('vm') @init('tutorial.SearchViewModel')">
+
            viewModel="@id('vm') @init('tutorial.SearchViewModel')">
<!-- omit other tags-->
+
...
 
</window>
 
</window>
</source>
+
</syntaxhighlight>
  
 
After binding the ViewModel to the component, all its child components can access the same ViewModel and its properties.  
 
After binding the ViewModel to the component, all its child components can access the same ViewModel and its properties.  
  
 +
 +
We can bind View to both ViewModel's properties and behavior with data binding expression. Let's see how to use data binding to achieve the search function.
  
  
Both ViewModel's properties and behavior can be bound to View with data binding expression. Let's see how to use data binding to achieve search function.
+
=== Load Data From a ViewModel ===
 +
Since we have declared variables in ViewModel class for a component's states in the previous section, we can bind the component's attributes to them. After binding a component's attribute to ViewModel, ZK will synchronize data between the attribute's value and a ViewModel's property for us automatically. We can specify '''which attribute is loaded from which property''' by writing data binding expression as a component attribute's value with the syntax:
  
We have declared variables in ViewModel class for component's states in previous section, and we can bind component's attributes to them. After binding a component's attribute to ViewModel, ZK will synchronize data between attribute's value and a ViewModel's property for us automatically. Now we are going to specify '''which attribute is bound to which property''' by writing data binding expression in a component attribute's value with syntax:
+
'''<code>@load(vm.aProperty) </code>'''
  
'''<tt>@bind(vm.myProperty) </tt>'''
+
* Remember that <code>vm</code> is the id we have given it in <code> @id()</code> previously and now we use it to reference ViewModel object.
  
* Remember that <tt>vm</tt> is the id we have given it in <tt> @id()</tt> previously and now we use it to reference ViewModel object.
 
  
There are 2 states which relate to search function to be stored in the ViewModel upon previous analysis. First, we want to store value of ''textbox'' in ViewModel's <tt>keyword</tt>. Then we can bind "value" of ''textbox'' to <tt>vm.keyword</tt> with <tt>@bind(vm.keyword)</tt>.  Second, We want to store the data model of a ''listbox'' in ViewModel's <tt>carList</tt>, so we should bind ''listbox'''s "model" to <tt>vm.carList</tt>.  
+
=== Save Data to a ViewModel ===
 +
There are 2 states which relate to search function in the ViewModel upon the previous analysis. First, we want to store value of ''textbox'' in ViewModel's <code>keyword</code>. We can then bind "value" of ''textbox'' to <code>vm.keyword</code> with <code>@save(vm.keyword)</code>. So that ZK will save the user input into the ViewModel at the proper moment.  Second, we want to assign the ''Listbox'' 's data with ViewModel's <code>carList</code>, so we should bind its "model" attribute to <code>vm.carList</code>.  
  
'''searchMvvm.zul'''
+
'''Extracted from searchMvvm.zul'''
<source lang="xml" high="3,6">
+
<syntaxhighlight line lang="xml" highlight="3,6">
  
 
<hbox>
 
<hbox>
 
Keyword:
 
Keyword:
<textbox value="@bind(vm.keyword)" />
+
<textbox value="@save(vm.keyword)" />
 
<button label="Search" image="/img/search.png"/>
 
<button label="Search" image="/img/search.png"/>
 
</hbox>
 
</hbox>
<listbox height="160px" model="@bind(vm.carList)" emptyMessage="No car found in the result">
+
<listbox height="160px" model="@load(vm.carList)" emptyMessage="No car found in the result">
 
<!-- omit other tags -->
 
<!-- omit other tags -->
  
</source>
+
</syntaxhighlight>
  
  
Only a component's event attribute (e.g. onClick) can be bound to ViewModel's behavior. After you bind an event to a ViewModel, each time a user triggers the event, ZK finds bound command method and invokes it. In order to handle clicking on "Search" button, we have to bind button's onClick attribute to a command method with following syntax:
+
===Invoke a Method of a ViewModel ===
 +
We can only bind a component's event attribute (e.g. onClick) to ViewModel's behavior. After we bind an event to a ViewModel, each time a user triggers the event, ZK finds the bound command method and invokes it. In order to handle clicking on "Search" button, we have to bind the button's onClick attribute to a command method with the following syntax:
  
'''<tt> @command('COMMAND_NAME')</tt>'''
+
'''<code> @command('COMMAND_NAME')</code>'''
  
* You should look for command name specified in your ViewModel's command method.  
+
* We should look for command name specified in our ViewModel's command method.  
  
'''searchMvvm.zul'''
+
'''Extracted from searchMvvm.zul'''
<source lang="xml" high="4">
+
<syntaxhighlight line lang="xml" highlight="4">
 
<hbox>
 
<hbox>
Name Keyword:
+
Keyword:
<textbox value="@bind(vm.keyword)" />
+
<textbox value="@save(vm.keyword)" />
 
<button label="Search" image="/img/search.png" onClick="@command('search')" />
 
<button label="Search" image="/img/search.png" onClick="@command('search')" />
 
</hbox>
 
</hbox>
<listbox height="160px" model="@bind(vm.carList)" emptyMessage="No car found in the result">
+
<listbox height="160px" model="@load(vm.carList)" emptyMessage="No car found in the result">
 
<!-- omit other tags -->
 
<!-- omit other tags -->
</source>
+
</syntaxhighlight>
  
After binding this "onClick" event, when a user clicks "Search" button, ZK will invoke <tt>search() </tt> and reload the property "carList" which is specified in <tt>@NotifyChange</tt>.
+
After binding this "onClick" event, when a user clicks "Search" button, ZK will invoke <code>search() </code> and reload the property "carList" which is specified in <code>@NotifyChange</code>.
  
== Display a Collection of Data ==
+
== Displaying Data Collection ==
 
<!--
 
<!--
 
use binding syntax
 
use binding syntax
 
-->
 
-->
  
The way to display a collection of data with data binding is very similar to the way in MVC approach. The only difference is you should use data binding expression instead of EL.
+
The way to display a collection of data with data binding is very similar to the way in the MVC approach.  we will use a special tag, <code> <template> </code><ref>[[ZK Developer's Reference/MVC/View/Template]]</ref>, to control the rendering of each item. The only difference is we should use data binding expression instead of EL.
 +
 
 +
Steps to use <code> <template> </code>:
 +
# Use '''<code><template></code>''' to enclose components that we want to create iteratively.
 +
# Set template's "name" attribute to "model". <ref> [[ZK Developer's Reference/MVC/View/Template/Listbox Template]]</ref>
 +
# Use implicit variable, '''each''', to assign domain object's properties to component's attributes.
  
<source lang="xml" high="7,8,9,10,11,12,13,14">
+
'''Extracted from searchMvvm.zul'''
 +
<syntaxhighlight line lang="xml" highlight="7,8,9,10,11,12,13,14">
  
<listbox height="160px" model="@bind(vm.carList)" emptyMessage="No car found in the result">
+
<listbox height="160px" model="@load(vm.carList)" emptyMessage="No car found in the result">
 
<listhead>
 
<listhead>
<listheader label="Name" />
+
<listheader label="Model" />
<listheader label="Company" />
+
<listheader label="Make" />
 
<listheader label="Price" width="20%"/>
 
<listheader label="Price" width="20%"/>
 
</listhead>
 
</listhead>
 
<template name="model">
 
<template name="model">
 
<listitem>
 
<listitem>
<listcell label="@bind(each.name)"></listcell>
+
<listcell label="@init(each.model)"></listcell>
<listcell label="@bind(each.company)"></listcell>
+
<listcell label="@init(each.make)"></listcell>
<listcell>$<label value="@bind(each.price)" />
+
<listcell>$<label value="@init(each.price)" />
 
</listcell>
 
</listcell>
 
</listitem>
 
</listitem>
 
</template>
 
</template>
 
</listbox>
 
</listbox>
</source>
+
</syntaxhighlight>
  
== Implement View Details Function ==
+
== Implementing View Details Functionality ==
  
The steps to implement view details function are similar to previous sections.  
+
The steps to implement the view details functionality are similar to previous sections.  
  
# We bind attribute <tt>selectedItem</tt> of ''listbox'' to the property <tt>vm.selectedCar</tt> to save selected domain object.
+
# We bind attribute <code>selectedItem</code> of ''listbox'' to the property <code>vm.selectedCar</code> to save selected domain object.
# Because we want to show selected car's details, we bind value of ''label'' and src of ''image'' to selected car's properties which can be access by chaining dot notation like <tt>vm.selectedCar.name</tt>.  
+
# Because we want to show selected car's details, we bind value of ''label'' and src of ''image'' to selected car's properties which can be access by chaining dot notation like <code>vm.selectedCar.price</code>.  
# Each time a user selects a ''listitem'', ZK saves selected car to the ViewModel. Then ZK reloads <tt>selectedCar</tt>'s properties to those bound attributes.
+
# Each time a user selects a ''listitem'', ZK saves selected car to the ViewModel. Then ZK reloads <code>selectedCar</code>'s properties to those bound attributes.
  
 
<!--
 
<!--
 
(Most users may think this behavior is natural.)
 
(Most users may think this behavior is natural.)
You may wonder why does ZK know to reload <tt>selectedCar</tt>'s properties when they are changed? Because ''setter method has default notification by default''', ZK will reload the target property changed by setter method automatically. You don't need to specify <tt>@NotifyChange</tt> to notify ZK the changed property itself.
+
We may wonder why does ZK know to reload <code>selectedCar</code>'s properties when they are changed? Because ''setter method has default notification by default''', ZK will reload the target property changed by setter method automatically. We don't need to specify <code>@NotifyChange</code> to notify ZK the changed property itself.
 
-->
 
-->
  
<source lang="xml" high="2,6,8,9,10,11">
+
<syntaxhighlight line lang="xml" highlight="2,6,8,9,10,11">
<listbox height="160px" model="@bind(vm.carList)" emptyMessage="No car found in the result"
+
<listbox height="160px" model="@load(vm.carList)" emptyMessage="No car found in the result"
selectedItem="@bind(vm.selectedCar)">
+
selectedItem="@save(vm.selectedCar)">
 
<!-- omit child components -->
 
<!-- omit child components -->
 
</listbox>
 
</listbox>
 
<hbox style="margin-top:20px">
 
<hbox style="margin-top:20px">
<image width="250px" src="@bind(vm.selectedCar.preview)" />
+
<image width="250px" src="@load(vm.selectedCar.preview)" />
 
<vbox>
 
<vbox>
<label value="@bind(vm.selectedCar.name)" />
+
<label value="@load(vm.selectedCar.model)" />
<label value="@bind(vm.selectedCar.company)" />
+
<label value="@load(vm.selectedCar.make)" />
<label value="@bind(vm.selectedCar.price)" />
+
<label value="@load(vm.selectedCar.price)" />
<label value="@bind(vm.selectedCar.description)" />
+
<label value="@load(vm.selectedCar.description)" />
 
</vbox>
 
</vbox>
 
</hbox>
 
</hbox>
</source>
+
</syntaxhighlight>
 
 
= Approach Comparison =
 
<!--
 
list strength for users
 
-->
 
 
 
The interaction picture at left side is MVC, and the one at right side is MVVM. The main differences are that Controller changes to ViewModel and there is a binder to synchronize data instead of a Controller in MVVM .
 
 
 
[[Image:tutorial-mvc.png | 440px ]][[File:tutorial-separator.jpg]][[File:tutorial-mvvm.png | 440px ]]
 
 
 
 
 
 
 
 
 
Both approaches can achieve many things in common, but there are still some differences between them. Each of two approaches has its strength. Building an application with MVC approach is more intuitive, because you directly control what you see. Its strength is that you have total control of components, so that you can create child components dynamically, control custom components, or do anything a component can do.
 
 
 
In MVVM, because ViewModel is loosely-coupled with View (it has no reference to components), one ViewModel may associate with multiple Views without modification. UI designers and programmers may work in parallel. If data and behavior do not change, a View's change doesn't cause modifying ViewModel. Besides, as ViewModel is a POJO, it is easy to perform unit test on it without any special environment. That means ViewModel has better reusability, testabiliby, and better resistance against View change.
 
 
 
 
 
To summarize, a comparison table is illustrated below:
 
  
<div style="margin-left:auto;margin-right:auto;width:70%;">
 
{| border="2" style="text-align:center; font-size:18; padding:10px;"
 
|+
 
! !! <center>MVC</center> !! <center>MVVM</center>
 
|-
 
! Coupling with View
 
| Loose with layout
 
| Loose
 
|-
 
! Coupling with Component
 
| Tight
 
| Loose
 
|-
 
! Coding in View
 
| Component ID
 
| Data binding expression
 
|-
 
! Controller Implementation
 
| &nbsp;Extends ZK's composer&nbsp;
 
| a POJO
 
|-
 
! UI Data Access
 
| Direct access
 
| Automatic
 
|-
 
! Backend Data Access
 
| Direct  access
 
| Direct  access
 
|-
 
! UI Updating
 
| Manipulate components
 
| &nbsp;&nbsp; Automatic(@NotifyChange) &nbsp;&nbsp;
 
|-
 
! Component Controlling Granularity
 
| Fine-grained
 
| Normal
 
|-
 
! Performance
 
| High
 
| Normal
 
|}
 
</div>
 
  
= Download =
+
You can view complete zul at [https://github.com/zkoss-demo/gettingStarted/blob/master/src/main/webapp/searchMvvm.zul Github]
  
[http://zkbooks.googlecode.com/files/tutorial-20120803.zip Example application project zip file]
 
  
Download the example application zip file. In Eclipse, select '''File \ Import \ Existing Projects into Workspace \ Select archive file''' to import example application zip file as a project to your Eclipse. Then follow the instructions in [[#Run an Application |Run an Application]] to run it.
+
{{Template:tutorial Approach Comparison}}
  
 
= References =  
 
= References =  
  
 
<references/>
 
<references/>

Latest revision as of 06:18, 22 December 2023

Introduction

This tutorial is intended for software developers who have experience in writing Java EE programs. We will guide you on how to build a modern web application with ZK. The target application we are going to build is a simple car catalog application. In this article, we will present an approach that is classified as the Model-View-ViewModel (MVVM) design pattern. Using this approach, ZK can control components for you automatically and it separates the UI from its controller clearly. In addition, you can also choose to go with the MVC approach that is covered in another tutorial [1].



Tutorial Objective

Our target application is a simple car catalog application. This application has two functions:

  1. Search cars.
    Enter a keyword in the input field, click Search and search results will be displayed in the car list below.
  2. View details.
    Click an item from the car list, the area below the car list will show the selected car's details including model, price, description, and preview.


Tutorial-searchexample.png


Start from Example Project

You can get the source code of this article and import it to your IDE without starting from scratch. Please follow the README to run the project.

If you want to start a new project, please refer to ZK Installation Guide/Quick Start.

Declaring Domain Class

The following is the domain object that represents a car.

public class Car {
	private Integer id;
	private String model;
	private String make;
	private String preview;
	private String description;
	private Integer price;
	//omit getter and setter for brevity
}

We then define a service class to perform the business logic (search cars) shown below:

public interface CarService {

	/**
	 * Retrieve all cars in the catalog.
	 * @return all cars
	 */
	public List<Car> findAll();
	
	/**
	 * search cars according to keyword in  model and make.
	 * @param keyword for search
	 * @return list of car that matches the keyword
	 */
	public List<Car> search(String keyword);
}

In this example, we have defined a class, CarServeImpl, that implements the above interface. For simplicity, it uses a static list object as the data model. You can rewrite it so that it connects to a database in a real application. Its implementation details are not in the scope of this article, please refer to source code repository.

Building User Interface

UI is a good start to building an application as it helps you define the scope of your application. ZK provides hundreds of readily made UI components, so developers can rapidly build their desired user interface by combining and mix-matching these components without having to create a page from scratch.

In ZK, you can use ZK User Interface Markup Language (ZUML), an XML-formatted language, to describe UI. By ZK's convention, the files to describe the user interface with ZUML uses .zul as the name suffix. In zul files, one component is represented as an XML element (tag) and you can configure each component's style, behavior, and function by setting XML element's attributes. (check ZK Component Reference for details)

In this example application, first of all, we want to use a Window with the specified title and normal border as our application's frame.


As Window is the outermost component, it is called the root component. Window is a commonly used container because it makes your web application look like a desktop application. Besides, it can also enclose other components. All other components inside Window are called its child components and should be put in <window>'s body.

Extracted from search.zul

1 	<window title="Search" border="normal" width="600px">
2 		<!-- put child components inside a tag's body -->
3 	</window>
  • Line 1: Specifying title bar text with title and make <window> display a normal border with border . For width attribute, use CSS like syntax such as 800px or 60%.


Our example application's user interface is divided into 3 areas within the <window> (from top to bottom):

  1. search function
  2. car list
  3. car details.
Tutorial-ui-3areas.png


Search Area

ZK components are like building blocks, you can combine and mix-match existing components to construct your desired UI. To allow users to search, we need a text to prompt users for input, a place to enter keywords, and a button for triggering the search. We can use the following ZK components to fulfill this requirement:

Extracted from search.zul

1 Keyword:
2 <textbox id="keywordBox" />
3 <button id="searchButton" label="Search" iconSclass="z-icon-search" style="margin: 0 0 5px 5px"/>
  • Line 1~2: Specifying the id attribute for some components allows you to control them by referencing their id.
  • Line 3: You can use built-in Font Awesome icon at iconSclass. Please refer to LabelImageElement#IconSclass for details.

Car List Area

ZK provides several components to display a collection of data such as listbox, grid, and tree. In this example, we use a listbox to display a list of cars with 3 columns: Model, Make, and Price. Here we use listcell with static label to demonstrate structure of a listitem. Later, we'll talk about how to create listitem dynamically with a collection of data.

Extracted from search.zul

 1 <listbox id="carListbox" emptyMessage="No car found in the result" rows="5">
 2     <listhead>
 3         <listheader label="Model" />
 4         <listheader label="Make" />
 5         <listheader label="Price" width="20%"/>
 6     </listhead>
 7     <listitem>
 8         <listcell label="car model"></listcell>
 9         <listcell label="make"></listcell>
10         <listcell>$<label value="price" /></listcell>
11     </listitem>
12 </listbox>
  • Line 1: rows determines the max visible row. emptyMessage is used to show a message when listbox contains no items.
  • Line 2: The listbox is a container component, and you can add listhead to define a column.
  • Line 7: The listitem is used to display data, and the number of listcell in one listitem usually equals to the number of listheader.

Car Details Area

hlayout and vlayout are layout components which arrange their child components in horizontal and vertical order.

Extracted from search.zul

1 	<hlayout style="margin-top:20px" width="100%">
2 		<image id="previewImage" width="250px" />
3 		<vlayout hflex="1">
4 			<label id="modelLabel" />
5 			<label id="makeLabel" />
6 			<label id="priceLabel" />
7 			<label id="descriptionLabel" />
8 		</vlayout>
9 	</hlayout>
  • Line 1: the style attribute allows you to customize component's style with CSS syntax.

Automatic UI Controlling

The approach we introduce here to control user interaction is to let ZK control UI components for you. This approach is classified to Model-View-ViewModel (MVVM) design pattern. [2] This pattern divides an application into three parts.

The Model consists of application data and business rules. CarService and other classes used by it represent this part in our example application.

The View means user interface. The zul page which contains ZK components represents this part. A user's interaction with components triggers events to be sent to controllers.

The ViewModel is responsible for exposing data from the Model to the View and providing required action requested from the View. The ViewModel is type of View abstraction which contains a View's state and behavior. But ViewModel should contain no reference to UI components. ZK framework handles communication and state synchronization between View and ViewModel.

Under this approach, we just prepare a ViewModel class with proper setter, getter and application logic methods, then assign data-binding expression to a component's attributes in a ZUL. There is a binder in ZK which will synchronize data between ViewModel and components and handle events automatically according to binding expressions. We don't need to control components by ourselves.


Here we use the search function to explain how MVVM works in ZK. Assume that a user click "Search" button then listbox updates its content. The flow is as follows:

Tutorial-mvvm.png


  1. A user clicks "Search" button and a corresponding event is sent.
  2. ZK's binder invokes the corresponding command method in the ViewModel.
  3. The method accesses data from Model and updates some ViewModel's properties.
  4. ZK's binder reloads changed properties from the ViewModel to update component's states.


Abstracting the View

ViewModel is an abstraction of View. Therefore when we design a ViewModel, we should analyze UI's functions for what state it contains and what behavior it has.

The state:

  1. keyword from user input
  2. car list of search result
  3. selected car

The operation:

  1. search


According to the above analysis, the ViewModel should have 3 variables for the above states and one method for the behavior. In ZK, creating a ViewModel is like creating a POJO, and it exposes its states like JavaBean's properties through setter and getter methods. The search method implements search logic with service class and updates the property "carList".

SearchViewModel.java

 1 package tutorial;
 2 
 3 import java.util.List;
 4 import org.zkoss.bind.annotation.*;
 5 
 6 public class SearchViewModel {
 7 
 8 	private String keyword;
 9 	private List<Car> carList;
10 	private Car selectedCar;
11 	
12 	//omit getter and setter
13 
14 	public void search(){
15 		carList = carService.search(keyword);
16 	}
17 }


Annotation

In ZK MVVM, any behavior that a View can request is a command in a ViewModel. We can bind a component's event to the command and ZK will invoke the method when a bound event is triggered. In order to let ZK know which behavior (method) can be requested, you should apply an annotation @Command on a method. We mark search() as a "command" with default command name, search, which is the same as method name. The command name is used in the data-binding expression we'll talk about in the next section.


In search(), we change a ViewModel's property: carList. Thus, we should tell ZK this change with @NotifyChange so that ZK can reload the changed property for us after it invokes this method.

For the "search" command, it looks like this:

SearchViewModel.java

 1 package tutorial;
 2 
 3 import java.util.List;
 4 import org.zkoss.bind.annotation.*;
 5 
 6 public class SearchViewModel {
 7 
 8 	//omit other codes
 9 
10 	@Command
11 	@NotifyChange("carList")
12 	public void search(){
13 		carList = carService.search(keyword);
14 	}
15 }


For complete source code, please refer to Github

Binding UI to ViewModel

Under MVVM, we build our UI as same as we would with the MVC approach, then we specify the relationship between a ZUL and a ViewModel by writing data binding expression in component's attribute and let ZK handle components for us.

Bind a ViewModel

To bind a component to a ViewModel, we should apply a composer called org.zkoss.bind.BindComposer. This composer processes data binding expressions and initializes the ViewModel class. We then bind this component to a ViewModel by setting its viewModel attribute with following syntax:

@id('ID') @init('FULL.QUALIFIED.CLASSNAME')

  • @id() is used to set ViewModel's id to whatever we want like a variable name. We will use this id to reference ViewModel's properties (e.g. vm.carList) in a data binding expression.
  • We should provide full-qualified class name for @init() to initialize the ViewModel object.


Extracted from searchMvvm.zul

1 	<window title="Search" width="600px" border="normal" 
2             viewModel="@id('vm') @init('tutorial.SearchViewModel')">
3 	...
4 	</window>

After binding the ViewModel to the component, all its child components can access the same ViewModel and its properties.


We can bind View to both ViewModel's properties and behavior with data binding expression. Let's see how to use data binding to achieve the search function.


Load Data From a ViewModel

Since we have declared variables in ViewModel class for a component's states in the previous section, we can bind the component's attributes to them. After binding a component's attribute to ViewModel, ZK will synchronize data between the attribute's value and a ViewModel's property for us automatically. We can specify which attribute is loaded from which property by writing data binding expression as a component attribute's value with the syntax:

@load(vm.aProperty)

  • Remember that vm is the id we have given it in @id() previously and now we use it to reference ViewModel object.


Save Data to a ViewModel

There are 2 states which relate to search function in the ViewModel upon the previous analysis. First, we want to store value of textbox in ViewModel's keyword. We can then bind "value" of textbox to vm.keyword with @save(vm.keyword). So that ZK will save the user input into the ViewModel at the proper moment. Second, we want to assign the Listbox 's data with ViewModel's carList, so we should bind its "model" attribute to vm.carList.

Extracted from searchMvvm.zul

1 		<hbox>
2 			Keyword:
3 			<textbox value="@save(vm.keyword)" />
4 			<button label="Search" image="/img/search.png"/>
5 		</hbox>
6 		<listbox height="160px" model="@load(vm.carList)" emptyMessage="No car found in the result">
7 		<!-- omit other tags -->


Invoke a Method of a ViewModel

We can only bind a component's event attribute (e.g. onClick) to ViewModel's behavior. After we bind an event to a ViewModel, each time a user triggers the event, ZK finds the bound command method and invokes it. In order to handle clicking on "Search" button, we have to bind the button's onClick attribute to a command method with the following syntax:

@command('COMMAND_NAME')

  • We should look for command name specified in our ViewModel's command method.

Extracted from searchMvvm.zul

1 		<hbox>
2 			Keyword:
3 			<textbox value="@save(vm.keyword)" />
4 			<button label="Search" image="/img/search.png" onClick="@command('search')" />
5 		</hbox>
6 		<listbox height="160px" model="@load(vm.carList)" emptyMessage="No car found in the result">
7 		<!-- omit other tags -->

After binding this "onClick" event, when a user clicks "Search" button, ZK will invoke search() and reload the property "carList" which is specified in @NotifyChange.

Displaying Data Collection

The way to display a collection of data with data binding is very similar to the way in the MVC approach. we will use a special tag, <template> [3], to control the rendering of each item. The only difference is we should use data binding expression instead of EL.

Steps to use <template> :

  1. Use <template> to enclose components that we want to create iteratively.
  2. Set template's "name" attribute to "model". [4]
  3. Use implicit variable, each, to assign domain object's properties to component's attributes.

Extracted from searchMvvm.zul

 1 		<listbox height="160px" model="@load(vm.carList)" emptyMessage="No car found in the result">
 2 			<listhead>
 3 				<listheader label="Model" />
 4 				<listheader label="Make" />
 5 				<listheader label="Price" width="20%"/>
 6 			</listhead>
 7 			<template name="model">
 8 				<listitem>
 9 					<listcell label="@init(each.model)"></listcell>
10 					<listcell label="@init(each.make)"></listcell>
11 					<listcell>$<label value="@init(each.price)" />
12 					</listcell>
13 				</listitem>
14 			</template>
15 		</listbox>

Implementing View Details Functionality

The steps to implement the view details functionality are similar to previous sections.

  1. We bind attribute selectedItem of listbox to the property vm.selectedCar to save selected domain object.
  2. Because we want to show selected car's details, we bind value of label and src of image to selected car's properties which can be access by chaining dot notation like vm.selectedCar.price.
  3. Each time a user selects a listitem, ZK saves selected car to the ViewModel. Then ZK reloads selectedCar's properties to those bound attributes.


 1 		<listbox height="160px" model="@load(vm.carList)" emptyMessage="No car found in the result"
 2 		selectedItem="@save(vm.selectedCar)">
 3 		<!-- omit child components -->
 4 		</listbox>
 5 		<hbox style="margin-top:20px">
 6 			<image width="250px" src="@load(vm.selectedCar.preview)" />
 7 			<vbox>
 8 				<label value="@load(vm.selectedCar.model)" />
 9 				<label value="@load(vm.selectedCar.make)" />
10 				<label value="@load(vm.selectedCar.price)" />
11 				<label value="@load(vm.selectedCar.description)" />
12 			</vbox>
13 		</hbox>


You can view complete zul at Github


Approach Comparison

Here is the architectural picture to demonstrate the interaction between Model, View, and Controller/ViewModel.

Tutorial-mvc.pngTutorial-mvvm.png

The main differences are that Controller changes to ViewModel and there is a binder in MVVM to synchronize data instead of a Controller.


MVC Advantages

  • very intuitive, easy to understand
  • control components in fine-grained

For those who use ZK for the first time or beginners, we suggest you using the MVC pattern. Because it's easy to use and debug.

MVVM Advantages

  • suitable for design-by-contract programming
  • loose coupling with View
  • better reusability
  • better testability
  • better for responsive design


Both approaches can achieve many things in common and have their own strength. But there are still some differences between them. Building an application with the MVC pattern is more intuitive because you directly control what you see. Its strength is that you have total control of components to create child components dynamically, control custom components, or do anything a component can do.

In the MVVM pattern, because ViewModel is loosely-coupled with View (it has no reference to components), one ViewModel may associate with multiple Views without modification. UI designers and programmers may work in parallel. If data and behavior do not change, a View's change doesn't cause ViewModel to be modified. In addition, as ViewModel is a POJO, it is easy to perform unit test on it without any special environment. That means ViewModel has better reusability, testability, and better resistance to View change.


To summarize, see the comparison table below:

MVC
MVVM
Coupling with View Loose with layout Loose
Coupling with Component Tight Loose
Coding in View Component ID Data binding expression
Controller Implementation  Extends ZK's composer  a POJO
UI Data Access Direct access Automatic
Backend Data Access Direct access Direct access
UI Updating Manipulate components    Automatic (@NotifyChange)   
Component Controlling Granularity Fine-grained Normal
Performance High Normal

References