It's common to want the user to confirm his action if it would be hard to reverse, e.g. if he asked to delete something. Here's one way to do this, using Javascript:
Link removeLink = new Link("removeLink") { @Override public void onClick() { // do something you want to confirm beforehand } }; removeLink.add( new SimpleAttributeModifier("onclick", "return confirm('are you sure?');"));
SimpleAttributeModifier
will replace any existing onclick
handler in the html. We can instead add our javascript to any existing javascript by attaching an IBehavior
object to the Link. First we define a class that implements IBehavior
:
class JavascriptEventConfirmation extends AbstractBehavior { private final String msg; private final String event; public JavascriptEventConfirmation(String event, String msg) { this.msg = msg; this.event = event; } @Override public void onComponentTag(Component component, ComponentTag tag) { String script = (String) tag.getAttributes().get(event); script = "confirm('" + msg + "'); " + script; tag.put(event, script); } }
Then we add the behavior instead of an attribute modifier:
removeLink.add(new JavascriptEventConfirmation("onclick", "are you sure?"));