Skip to content

EventListener

Redempt edited this page Dec 23, 2020 · 3 revisions

One of the common issues with Spigot is that you have to define and instantiate a new class to create an event listener. RedLib offers a way to define a listener inline, easily.

EventListener allows you to easily register a listener, and even specify its priority if you need to. All you have to do is instantiate it, and it will be immediately registered for the given event. You just pass it the plugin registering the listener, the event class, and a lambda to handle the event:

new EventListener<>(plugin, PlayerMoveEvent.class, e -> {
	//Do stuff
});

If you need to specify the priority, you can do so by passing an EventPrriority between the event class and handler:

new EventListener<>(plugin, PlayerMoveEvent.class, EventPriority.HIGH, e -> {
	//Do stuff
});

The primary use for an EventListener is when you have to listen for a certain entity or player to fire a certain event. In those cases, you always want to unregister the listener afterwards. Because of this, EventListener has an alternative constructor which takes a BiConsumer<EventListener, T> instead of a Consumer<T>, with T being the event type.

//If you tried to assign this to a variable and call unregister() on it within the lambda, it would give a compiler error.
new EventListener<>(plugin, EntityDeathEvent.class, (l, e) -> {
	//Do stuff
	//Unregister the listener
	l.unregister();
});
Clone this wiki locally