In the previous issue of the JSF 2 introduction series, I discussed automating composite components with built-in AJAX implementations. The page author can use the component in a facelet that handles all Ajax details. Although the built-in Ajax already exists, it is easy for the page author to add Ajax to the component after the developer implements the composite component, possibly for a long time. This article shows how the composite component accommodates the Ajax that was added later.
As discussed in the JSF 2 Introduction, part 3rd: event handling, JavaScript, and Ajax, the JSF 2 <f:ajax> tag allows page authors to add later Ajax to the built-in components of JSF 2. For example, with <f:ajax>, you can easily turn a submit button into an Ajax button:
<f:ajax>
However, the JSF 2 <f:ajax> tag does not process composite components (indeed), because composite components are just component containers.
For example, in the introduction to JSF 2, part 2nd: Templates and composite components, I introduced a simple icon composite component that contains a link, represented by an image. When the user clicks the icon, the link submits a form that triggers a server-side action listener that is associated with the icon link. Using icons is simple:
<util:icon image="...">
<f:actionListener for="link" type="...">
</util:icon>
Because you can use the <f:ajax> tag to turn the Submit button to an Ajax button, you might think you can do the same thing with the icon:
<util:icon image="...">
<f:ajax>
<f:actionListener for="link" type="...">
</util:icon>
The code snippet above will not take effect because I have attached a <f:ajax> tag to the icon component, and what I really want to do is attach it to the link inside the icon.
In this case, what I need is a mechanism that allows me to attach Ajax behavior to the inside of an icon, or more generally, allow me to attach Ajax behavior to components within a composite component. This mechanism (implemented in Mojarra and Apache myfaces and not recorded in JSF 2.0) is the focus of this article. (Note: myfaces support was added when writing this article.) Before I know how the mechanism works, I'll create a new icon composite component for use.
Reusable icon Components
Imagine you have one of the coolest jobs in the world. Perhaps you are implementing a new generation of World of Warcraft graphics engine. But sadly, it's just a dream. Today, you want to implement the font selector as shown in Figure 1:
Figure 1. Select a font