Hooks

This page describes how to create and register hooks.

A hook is a set of instructions to be executed when an inventory event is performed for a specific inventory.

How to create a hook?

Hooks are represented by the generic Hook functional interface. The following code illustrates how to create a hook.

Hook<FastInventoryBeforeOpenEvent> hook = event -> {
    System.out.println("Hook called before opening the inventory");
};

Hooks can be applied on the following events:

  • FastInventoryBeforeOpenEvent: Called before opening an inventory.

  • FastInventoryAfterOpenEvent: Called after an inventory has been opened.

  • FastInventoryClickEvent: Called when a player clicks on an item.

  • FastInventoryCloseEvent: Called when an inventory is closed.

Register a hook

Hooks are registered specifically for an inventory in its inventory descriptor by redefining the addHooks(HookManager manager) method.

The HookManager interface provides the addHook(hookId, eventClass, hook) method to register a new hook.

public class CustomInventoryDescriptor implements InventoryDescriptor {
    
    ...
    
    @Override
    public void addHooks(HookManager manager) {

        manager.addHook("before-open", FastInventoryBeforeOpenEvent.class, event -> {
            System.out.println("Hook called before opening the inventory.");
        });

        manager.addHook("after-open", FastInventoryAfterOpenEvent.class, event -> {
            System.out.println("Hook called after the inventory has been opened.");
        });

        manager.addHook("close", FastInventoryCloseEvent.class, event -> {
            System.out.println("Hook called when the inventory is closed.");
        });

        manager.addHook("click", FastInventoryClickEvent.class, event -> {
            System.out.println("Hook called when the inventory viewer clicks on an item in the inventory.");
        });
    }
    
    ...

}

Additional information

In CraftVentory, we do not rely on Bukkit events. Indeed, we prefer using hooks which are registered and executed specifically for an inventory instead of events which are executed for all inventories.

Last updated