Using callbacks
Callbacks are a modern replacement for Bukkit's events. They are multi-platform and can be intercept and modified by using handlers or listeners.
- Handlers provide access to the callback's object so that it can be handled, hence the name.
- Listeners give access to the object's parameters, which are mirrored from the callback's constructor and passed to the listener when a callback is handled. Listeners cannot modify the object at all, they just listen to the result.
Source: callbacks at GitHub
In short, if you want to modify the event you'll want to use a handler. On the other hand, if you're only listening to the event, you'll use a listener (which comes with performance benefits!).
Registering a handler
Let's register a handler for the SocialMessageReceiveCallback. We'll cancel the callback if the channel is not the default channel, just as a demonstration:
var instance = SocialMessageReceiveCallback.INSTANCE;
var identifier = "plugin:handler-name"; // The NAMESPACED identifier for our handler. We recommend using your plugin's name and a descriptive handler namre
instance.registerHandler(identifier, callback -> {
ChatChannel defaultChannel = Social.get().getChatManager().getDefaultChannel();
if (!callback.channel().equals(defaultChannel)) {
callback.cancelled(true);
}
});
Registering a listener
Now let's do the same with a listener, except we'll call a local method instead of cancelling the event in this example. We'll also use a proper IdentifierKey
instead of a namespaced string, just to show a different approach:
var instance = SocialMessageReceiveCallback.INSTANCE; // The instance of the callback
var key = IdentifierKey.of("plugin-name", "listener-name");
instance.registerListener(key, (sender, recipient, channel, message, messageId, replyId, cancelled) -> {
doLocalStuff(sender, message);
});
Warning
Don't forget that listeners cannot modify the event in any way. You'll want to use handlers for that.