The "client behavior" idea refer to the fact that a client
(user) can perform an action over a component (click, blur, focus, mouse over,
mouse out, etc) and trigger a specific behavior. As you can see, the actions
performed by the user will cause HTML events (e.g. onchange, onclick, onmouseover, onmouseout,
onkeydown, onload), and those events will be transformed in behaviors
via JavaScript snippets of code that runs on client machine, in his browser. The
behaviors was already rendered by JSF as pieces of JavaScript, and there are available
on client.
Technically speaking, the ClientBehavior interface (and the ClientBehaviorBase which is a
convenience base class that implements the default concrete behavior of all
methods defined by ClientBehavior)
defines the mechanism by which client behavior implementations generate
scripts. The most important method on the ClientBehavior interface is getScript():
public String
getScript(ClientBehaviorContext context)
The getScript()
method returns a string that contains a JavaScript code suitable for inclusion
in a DOM event handler. The method’s single argument, the ClientBehaviorContext,
provides access to information that may be useful during script generation,
such as the FacesContext
and the UIComponent
to which the behavior is being attached.
Let's see an example. We simply render a button that is capable to
delete some files when is clicked. But, before deleting the files we render a
confirmation dialog. The piece of JavaScript that output the confirmation
dialog is returned by a ClientBehaviorBase,
and the HTML event is onclick
- this is the default event for <h:commandButton/>.
1.
The index.xhtml
page looks like this:
<h:body>
<h:form>
<h:commandButton value="Delete"
action="done">
<b:confirmDelete/>
</h:commandButton>
</h:form>
</h:body>
2.
The ClientBehaviorBase looks
like this:
@FacesBehavior(value
= "confirm")
public class
ConfirmDeleteBehavior extends ClientBehaviorBase {
@Override
public String getScript(ClientBehaviorContext
behaviorContext) {
return "return confirm('Are you sure you
want to delete this file ?');";
}
}
3. The delete.taglib.xml looks
like this:
<facelet-taglib
version="2.2"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-facelettaglibrary_2_2.xsd">
<namespace>http://www.custom.tags/jsf/delete</namespace>
<tag>
<tag-name>confirmDelete</tag-name>
<behavior>
<behavior-id>confirm</behavior-id>
</behavior>
</tag>
</facelet-taglib>
The complete example is available here.
Niciun comentariu :
Trimiteți un comentariu