Inspired by the event-driven architecture of JavaScript, this project is aimed to facilitate the comprehension of EDA.
A set of API is implemented quite similar to Event
, EventTarget
and EventListener
in JavaScript.
Create an Event
// Create a custom event
Event event = new Event();
event.type = /* type string */;
event.args = /* any object */;
// then dispatch this event somewhere.
Add an Event Listener
// Create and instantiate an event target.
EventTarget target = new EventTarget() {};
// Create and implement an event listener.
EventListener listener = new EventListener() {
@Override
public void on(Event event) {
switch(event.type) {
case "event_type":
// TODO: handle event typed of "event_type".
break;
default:
break;
}
}
};
// Add event listeners
target.addEventListener("event_type", listener);
// Dispatch an event
target.dispatch(event);
Remove an Event Listener
// Remove a specific event listener
target.removeEventListener("event_type", listener);
// Remove all listeners of a specific event
target.removeEventListener("event_type");
// Remove all listeners
target.removeEventListener();
You can implement an event target from EventTarget
or an event listener from EventListener
.
Implement an Event Target
public class SampleEventTarget extends EventTarget {
// TODO: dispatch an event somewhere.
@Override
public void dispatch(Event event) {
// TODO: dispatch event.
}
}
Implement an Event Listener
public class SampleEventListener extends EventListener {
@Override
public void on(event) {
switch (event.type) {
case "event_type":
// TODO: handle event typed of "event_type".
break;
default:
break;
}
}
}
You can implement an event target wrapper from IEventTarget
or an event listener wrapper from IEventHandler
.
An Event Target Wrapper Implementing IEventTarget
public class SampleEventTargetWrapper implements IEventTarget {
private EventTarget mEventTarget = new EventTarget {
};
@Override
public void addEventListener(String type, IEventHandler listener) {
mEventTarget.addEventListener(type, listener);
}
@Override
public void removeEventListener(String type, IEventHandler listener) {
mEventTarget.removeEventListener(type, listener)
}
@Override
public void removeEventListener(String type) {
mEventTarget.removeEventListener(type);
}
@Override
public void dispatch(Event event) {
mEventTarget.dispatch(event);
}
}
An Event Listener Wrapper Implementing IEventHandler
public class SampleEventListenerWrapper implements IEventHandler {
private EventListener mEventListener = new EventListener() {
@Override
public void on(Eevnt event) {
switch (event.type) {
case "event_type":
// TODO: handle event typed of "event_type".
break;
default:
break;
}
}
};
@Override
public void invoke(Event event) {
mEventListener.invoke(event);
}
@Override
public void on(Event event) {
mEventListener.on(event);
}
}
MIT.