Before checking this application, please get familiar with client
behaviors. A simple example is available here.
Now, let's write a generic client behavior example. We simply want to
display an image, and react via a JS snippet of code to the following events that occur on this image: onclick, onmouseout,
onmouseover, onmousedown and onmouseup.
1.
The index.xhtml
looks like this:
<h:body>
<h:panelGrid columns="2">
<h:graphicImage
library="default" name="pfof.png">
<b:genericBehavior/>
</h:graphicImage>
<div id="behaviorsId"
style="width:300px;"/>
</h:panelGrid>
</h:body>
2.
We use a tag handler to programmatically register behaviors:
public class
GenericBehaviorTagHandler extends TagHandler {
private final GenericBehaviorHandler
onmouseout = new GenericBehaviorHandler();
private final GenericBehaviorHandler
onmouseover = new GenericBehaviorHandler();
private final GenericBehaviorHandler onclick =
new GenericBehaviorHandler();
private final GenericBehaviorHandler
onmousedown = new GenericBehaviorHandler();
private final GenericBehaviorHandler onmouseup
= new GenericBehaviorHandler();
public GenericBehaviorTagHandler(TagConfig
tagConfig) {
super(tagConfig);
}
@Override
public void apply(FaceletContext ctx,
UIComponent parent) throws IOException {
if (parent instanceof ClientBehaviorHolder) {
ClientBehaviorHolder clientBehaviorHolder = (ClientBehaviorHolder)
parent;
Map<String, List<ClientBehavior>> behaviors =
clientBehaviorHolder.getClientBehaviors();
if
(!(behaviors.containsKey("mouseout"))
&&
!(behaviors.containsKey("click"))
&&
!(behaviors.containsKey("mouseover"))
&& !(behaviors.containsKey("mousedown"))
&&
!(behaviors.containsKey("mouseup"))) {
clientBehaviorHolder.addClientBehavior("mouseout",
onmouseout);
clientBehaviorHolder.addClientBehavior("mouseover",
onmouseover);
clientBehaviorHolder.addClientBehavior("click", onclick);
clientBehaviorHolder.addClientBehavior("mousedown",
onmousedown);
clientBehaviorHolder.addClientBehavior("mouseup", onmouseup);
}
}
}
}
3.
The behaviors are instances of GenericBehaviorHandler:
public class
GenericBehaviorHandler extends ClientBehaviorBase {
@Override
public String getRendererType() {
return "genericbehaviorrenderer";
}
}
4.
And the behavior renderer is:
@FacesBehaviorRenderer(rendererType
= "genericbehaviorrenderer")
public class
GenericBehaviorRenderer extends ClientBehaviorRenderer {
@Override
public String getScript(ClientBehaviorContext
behaviorContext, ClientBehavior behavior) {
return
"document.getElementById('behaviorsId').innerHTML += '" +
behaviorContext.getEventName() + " |';";
}
}
The complete example is available here.
Niciun comentariu :
Trimiteți un comentariu