Skip to content
Shanyu Thibaut Juneja edited this page Jul 16, 2023 · 1 revision

Listeners

How to listen to events? Well, Fairy comes pre-packaged with an event listening injection. Tired of calling bukkit to initialize your listener? Well, we've got that covered. All you need to do is initialize your class as a component and specify you wish for it to be injected as a listener:

Simple Listener

@InjectableComponent
@@RegisterAsListener
public void MyListener implements Listener {

    @EventHandler
    public void handleJoin(final PlayerJoinEvent event) {
        System.out.prinln("Omg it works!!");
    }
}

Complex listener

Being a component, you can also autowire any other component into it. This means you can do things like this:


@RegisterAsListener
@InjectableComponent
public class GeneratorBlockSafetyListener implements Listener {

    @Autowired
    private GeneratorBlockService generatorBlockService;

    @EventHandler
    public void onDestroyGenerator(final BlockExplodeEvent event) {
        event.blockList().removeIf(block -> generatorBlockService.getGenerator(block) != null);
    }

    @EventHandler
    public void onDestroyGenerator(final BlockBreakEvent event) {
        event.setCancelled(
                generatorBlockService.getGenerator(event.getBlock()) != null
        );
    }
}

@Service(depends = {StorageRegistry.class})
public class GeneratorBlockService {
    @Autowired
    private StorageRegistry registry;

    private Map<Position, GeneratorBlock> blocks;

    @PostInitialize
    public void onPostInitialize() {
        this.blocks = new ConcurrentHashMap<>();
        this.registry.getGeneratorBlockStorage().all().forEach(e -> blocks.put(e.getPosition(), e));

        Fairy.getTaskScheduler().runRepeated(() -> {
            blocks.values().forEach(GeneratorBlock::tick);
        }, 20, 20);
    }

    public GeneratorBlock getGenerator(final Block block) {
        return blocks.get(new Position(
                block.getWorld().getName(),
                block.getX(),
                block.getY(),
                block.getZ()
        ));
    }
}
Clone this wiki locally