I need to write a custom ValueChangeHandler
and call out onValueChange(ValueChangeEvent)
. However I don't understand how to write a ValueChangeEvent
.
Maybe I understand the entire GWT event system wrong. Can anyone help?
Edit: I am asking how to create my own class that dispatches the ValueChangeEvent. I understand how to listen to it.
The constructor of ValueChangeEvent is not visible and I can't create it.
If you want to fire a ValueChangeEvent
you must implement the interface HasValueChangeHandlers
by or your class or somewhere in the class.
A simple implementation would be to use the EventBus:
EventBus bus = new SimpleEventBus();
@Override
public void fireEvent(GwtEvent<?> event) {
bus.fireEvent(event);
}
@Override
public HandlerRegistration addValueChangeHandler(ValueChangeHandler<T> handler) {
return bus.addHandler(ValueChangeEvent.getType(), handler);
}
Note you need to substitute T
with the type you want to fire.
Because you can't create a ValueChangeEvent directly dispatching an event is done via the fire method:
ValueChangeEvent.fire(this, value);
Where this
refers to the class/field implementing the HasValueChangeHandlers
and value
refers to the value that has been changed and you want to dispatch the event.
Actually, instead of creating a new EventBus or HandlerManager, as your widget will be a subclass of Wiget, it the standard way would be to use the Widget.addHandler(handler, eventType) method. Here's a minimal example:
public class MyWidget<T> extends Composite implements HasValueChangeHandlers<T>, HasValue<T> {
private T value;
public MyWidget() {
// Initialize stuff
}
@Override
public HandlerRegistration addValueChangeHandler(final ValueChangeHandler<T> handler) {
return addHandler(handler, ValueChangeEvent.getType());
}
@Override
public T getValue() {
return value;
}
@Override
public void setValue(T value) {
setValue(value, false);
}
@Override
public void setValue(T value, boolean fireEvents) {
this.value = value;
if (fireEvents) {
ValueChangeEvent.fire(this, getValue());
}
}
}
Really late to answer, but I've just solved this problem like this:
ValueChangeEvent.fire(hasValueChangeHandlerInstance, getValue());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With