简单事件和 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();
}