How to emit and handle custom events?

In general:

  1. Create a desired EventType.
  2. Create the corresponding Event.
  3. Call Node.fireEvent().
  4. Add Handlers and/or Filters for EventTypes of interest.

Some explanations:

If you want to create an event cascade, start with an “All” or “Any” type, that will be the root of all of the EventTypes:

EventType<MyEvent> OPTIONS_ALL = new EventType<>("OPTIONS_ALL");

This makes possible creating descendants of this type:

EventType<MyEvent> BEFORE_STORE = new EventType<>(OPTIONS_ALL, "BEFORE_STORE");

Then write the MyEvent class (which extends Event). The EventTypes should be typed to this event class (as is my example).

Now use (or in other words: fire) the event:

Event myEvent = new MyEvent();
Node node = ....;
node.fireEvent(myEvent);

If you want to catch this event:

Node node = ....;
node.addEventHandler(OPTIONS_ALL, event -> handle(...));
node.addEventHandler(BEFORE_STORE, event -> handle(...));

Leave a Comment