簡單事件和 EventHandler 使用語法

HanlderManager 提供:

public class HandlerManagerProvider {

    private static HandlerManager handlerManager;

    private HandlerManagerProvider() {
        
    }
    
    public static HandlerManager get() {
        return handlerManager != null ? handlerManager : (handlerManager = new HandlerManager(null));
    }
}

事件處理程式:

import com.google.gwt.event.shared.EventHandler;

public interface CustomEventHandler extends EventHandler {

    void doMyAction(CustomEvent event);

}

事件:

import com.google.gwt.event.shared.GwtEvent;

public class CustomEvent extends GwtEvent<CustomEventHandler> {

    public static final Type<CustomEventHandler> TYPE = new Type<>();

    @Override
    public Type<CustomEventHandler> getAssociatedType() {
        return TYPE;
    }

    @Override
    protected void dispatch(CustomEventHandler) {
        handler.doMyAction(this);
    }

}

處理事件(程式碼片段):

import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.event.shared.HandlerRegistration;

[...]

private List<HandlerRegistration> registrations = new ArrayList<>();
private final HandlerManager handlerManager = HandlerManagerProvider.get();

private void bind() {
    registrations.add(handlerManager.addHandler(CustomEvent.TYPE, new CustomEventHandler() {

        @Override
        public void doMyAction(CustomEvent event) {
            //Action after event firing
        }
    }));
}

射擊事件(程式碼片段):

private final HandlerManager handlerManager = HandlerManagerProvider.get();

public void fireEvent() {
    handlerManager.fireEvent(new CustomEvent());
}

在例如某些視窗銷燬之後清理註冊(不再需要此視窗的事件處理):

private void clearRegistrations() {
    for (HandlerRegistration registration : registrations)
        registration.removeHandler();
    registrations.clear();
}