I’ve mentioned the event/messaging system in my top five reasons you should be using Wicket post. Here let’s take a more in-depth look at usage and demonstrate an initialization pattern that can greatly improve your code.
Wicket events are a way for components and pages to communicate with each other. Using this feature we can create very complex, yet decoupled, component structures. A component can broadcast a message without needing to know who will receive the message. When a component is interested in a particular type of message, it can simply register to be notified when that message is broadcast.
Basic usage
When sending an event/message in Wicket, you need to specify three things:
- Destination – This can be the WebPage or a specific component.
- Broadcast type – This dictates the order in which the event is propogated to the child components of the destination. The options include breadth-first, depth-first, bubble-up, and exact. You would choose the type based on whether you want the children to recieve the event first, or the parent. If you only want to send the event to the destination without propogation, you would use an exact broadcast.
- Payload – Any additional data you want to send with the event. Typically you would at least include the AjaxRequestTarget so that receivers can use it to add components to the target.
Broadcasting an event with payload
Let’s look at an example of how to broadcast an event. We define a class CriticalUpdate which will be our payload. We broadcast to the parent WebPage using breadth-first propagation meaning the WebPage will receive the event first, followed by its children.
send(getPage(), Broadcast.BREADTH, new CriticalUpdate(target, payload));
Responding to the event
Any component that wants to receive the CriticalUpdate event would do so by overriding the onEvent() method:
public void onEvent(IEvent<?> event) {
if (event.getPayload() instanceof CriticalUpdate) {
CriticalUpdate msg = (CriticalUpdate) event.getPayload();
//do something with the msg
}
}
Using event-based component initialization
A pattern you can use that will make it easier for you to create your component hierarchies is event-based initialization. The idea is to add all of your UI elements (components, Panels, fields) to the WebPage with a constructor that does a minimum amount of work to initialize without actually creating any child components.
Then when you are done adding all of your components you broadcast an initialization event to the WebPage which will be propagated to all the child components. Upon receiving the event, they can create child components and any other initialization that is needed. This is the approach I use in my Wicket UI library.
The main advantage of this approach is when your components initialize themselves in response to the event, you have access to its parent container and to the page. This gives you more flexibility in your code because your Panel/Component is more aware of its environment.