Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

No Format
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import wicket.Component;
import wicket.Response;
import wicket.behavior.IBehavior;
import wicket.markup.ComponentTag;
import wicket.markup.html.IHeaderContributor;

/**
 * Represents a composite behavior allowing the user to attach multiple behaviors to a 
 * component at once. 
 *
 */
public class CompositeBehavior implements IBehavior, IHeaderContributor {
	
	private List<IBehavior> _behaviors; 
	
	public CompositeBehavior(IBehavior[] aBehaviors) { 
		_behaviors = new ArrayList<IBehavior>(Arrays.asList(aBehaviors));
	}
	
	public void add(IBehavior aBehavior) { 
		_behaviors.add(aBehavior);
	}

	public void bind(Component aComponent) {
		for (IBehavior behavior: _behaviors) { 
			behavior.bind(aComponent);
		}
	}

	public void detachModel(Component aComponent) {
		for (IBehavior behavior: _behaviors) { 
			behavior.detachModel(aComponent);
		}
	}

	public void exception(Component aComponent, RuntimeException aException) {
		for (IBehavior behavior: _behaviors) { 
			behavior.exception(aComponent, aException);
		}
	}

	public void onComponentTag(Component aComponent, ComponentTag aTag) {
		for (IBehavior behavior: _behaviors) { 
			behavior.onComponentTag(aComponent, aTag);
		}
	}

	public void rendered(Component aComponent) {
		for (IBehavior behavior: _behaviors) { 
			behavior.rendered(aComponent);
		}
	}

	public void renderHead(Response aResponse) {
		for (IBehavior behavior: _behaviors) {
			if ( behavior instanceof IHeaderContributor) { 
			    ((IHeaderContributor)behavior).renderHead(aResponse);
			}
		}
	}

}

At construction, the behavior is passed a list of behaviors that it must use. In the bind method of the composite behavior, the composite behavior adds each of its individual behaviors to the component to make sure they are used. Note that the composite behavior also implements IHeaderContributor so that header contributions are also taken into account.

Using this composite behavior, defining a confirmation behavior is just as easy as creating a subclass and passing in the two behaviors that it requires.