Chapter 4: Controlling Components"

From Documentation
Line 59: Line 59:
  
 
= Control in Controller =
 
= Control in Controller =
 
+
<!--
 
* what is composer
 
* what is composer
 
* how to apply it on a zul
 
* how to apply it on a zul
Line 65: Line 65:
 
* dynamic create components
 
* dynamic create components
 
* event listener
 
* event listener
 +
-->
 +
 +
The most commonly-used architecture to divide a application is ''MVC'',
 +
Java code to control components or handling events in <tt><zscript></tt>

Revision as of 10:06, 11 January 2013

ZK's Components are not just only for constructing user interface, we even can control them. In this chapter, we continue to use the last chapter's example but we remove 3 item's hyper links in the sidebar and replace them with redirecting action. To achieve this, we should write codes in Java for each item to response a user's clicking and redirect the user to an external site.

Control in Zscript

The simplest way to response a user's clicking is to write a event listener method and invoke it in onClick attribute. We could define a event listener in Java inside a <zscript> element and those codes will be interpreted when the ZUL is visited. This element also allows other script language like Javascript, Ruby, or Groovy.

Event listener redirect()

<grid hflex="1" vflex="1" sclass="sidebar">
	<zscript><![CDATA[
		//zscript code, it runs on server site, use it for fast prototyping
		java.util.Map sites = new java.util.HashMap();
		
		sites.put("zk","http://www.zkoss.org/");
		sites.put("demo","http://www.zkoss.org/zkdemo");
		sites.put("devref","http://books.zkoss.org/wiki/ZK_Developer's_Reference");
		
		
		void redirect(String name){
			String loc = sites.get(name);
			if(loc!=null){
				execution.sendRedirect(loc);
			}
		}
	]]></zscript>
...
  • Line 11: Define a event listener method like normal Java method and it redirects a browser according to passed key.
  • Line 14: execution is a implicit variable


After defining the event listener, we should specify it in the event attribute onClick because we want to invoke the event listener when clicking.

<grid>
	...
	<rows>
		<row sclass="sidebar-fn" onClick='redirect("zk")'>
			<image src="/imgs/site.png"/> ZK
		</row>
		<row sclass="sidebar-fn" onClick='redirect("demo")'>
			<image src="/imgs/demo.png"/> ZK Demo
		</row>
		<row sclass="sidebar-fn" onClick='redirect("devref")'>
			<image src="/imgs/doc.png"/> ZK Developer Reference
		</row>
	</rows>
</grid>

Through above steps, now if you click a Row of the Grid in the sidebar, your browser will be redirected to corresponding site.

This approach is very simple and fast, so it is especially suitable for building prototype. But if you need a better architecture for your application, you had better separate these codes from a ZUL.

Control in Controller

The most commonly-used architecture to divide a application is MVC, Java code to control components or handling events in <zscript>