You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 3 Next »

Table of contents

Howto create and use composite behaviors

It often occurs that multiple wicket behaviors must be used to obtain a certain effect. An example can be a tooltip that requires both a javascript header contribution and an attribute modifier. Another example is that of a confirmation popup when someone clicks on an certain button. Using a composite behavior, which is an example of the composite design pattern, it is posisble to realize things like this by adding just a single composite behavior object to a component (e.g. ToolTipBehavior, ConfirmationBehavior) instead of having to add multiple behaviors just to obtain one effect in the user interface. This enhances readability and maintainability of the code.

Adding confirmation messages, the traditional way

A straightforward example is a confirmation message that asks a user to confirm a (potentially) destructive action before proceeding. One way of doing this is using an attribute on an HTML element that requires confirmation,

   <a href="..." confirmationMessage="Are you sure?">link text</a>

together with javascript that inspects the confirmationMessage attribute and when it's there intercepts the onClick event


function confirmModifyOnclickImpl(element) {
	if (element.nodeType == 1) {
		var attribute = element.getAttribute("confirmationMessage");
		if (attribute) {
			var oldonclick = element.onclick;
			element.onclick = function () {
				var result = confirm(attribute);
				if (!result) {
					return result;
				}
				if (oldonclick) {
					return oldonclick();
				} else {
					// no special actions
				}
			};
		}
	}
	if ((element.nodeType == 1) || (element.nodeType == 9)) {
		var children = element.childNodes;
		for (var i = 0; i < children.length; i++) {
			confirmModifyOnclickImpl(children[i]);
		}
	}
}
function confirmModifyOnclick() {
	confirmModifyOnclickImpl(document);
}

runOnLoad(confirmModifyOnclick);

In the above example, the runOnLoad function is a function defined elsewhere that makes sure that the confirmModifyOnclick function is run when the document is loaded.

  • No labels