Saturday 16 June 2012

Wicket Inter-component events example



Wicket 1.5.x brings  Inter-component events, what you can do with this is make autoupdateable components based on events sended by other components,
 I will show you easy and simple example how to do this.


Application for this example contans of one label and one ajax link, on ajax link click label should autoupdate. Ajax link does not know witch components are listening this event, it just changes model on click.

Model is for this example shared between label and ajax link, what you can do is to send model with event..

We have EventListenerLabel that extends Label:

public class EventListenerLabel extends Label {
public EventListenerLabel(String id,IModel<Integer> model) {
super(id,model);
setOutputMarkupId(true);
}
@Override
public void onEvent(IEvent<?> event) {
if (event.getPayload() instanceof UpdateEvent) if this is update event refresh i
                 {
Event update = (Event)event.getPayload();
                        update.getTarget().add(this);
                  }
}
}


Then we have  EventSenderAjaxLink that extends AjaxLink<Integer>:


public class EventSenderAjaxLink extends AjaxLink<Integer> {

public EventSenderAjaxLink(String id, IModel<Integer> model) {
super(id, model);
}

@Override
public void onClick(AjaxRequestTarget target) {
Integer obj= getModelObject();
setModelObject(++obj);//change model value
send(getPage(), Broadcast.BREADTH, new UpdateEvent(target)); //send event on click.

}

}


Page where this is shown is EventExamplePage :


public class EventExamplePage extends WebPage {


public EventExamplePage() {

IModel<Integer> model = new Model<Integer>(0);


add(new EventListenerLabel("label", model));
add(new EventSenderAjaxLink("link", model));


}


}




Then we have UpdateEvent, AbstractEvent classes and Event interface.


public interface Event {
public AjaxRequestTarget getTarget();
}



public class AbstractEvent {
private final AjaxRequestTarget target;


    public AbstractEvent(AjaxRequestTarget target)
    {
        this.target = target;
    }
    public AjaxRequestTarget getTarget()
    {
        return target;
    }
}





public class UpdateEvent extends AbstractEvent implements Event{


public UpdateEvent(AjaxRequestTarget target) {
super(target);
}


}




This is one way to use events in wicket.
    Hope that this was helpfull to you.

1 comment: