Skip to content

EventBus

This page covers the information needed for you to create an Event Bus that you can use later.

What is an Event Bus?

An Event Bus is a system used to dispatch events to listeners. Instead of directly calling code from one part of your mod to another, events are posted to the bus, and any registered listeners receive them automatically.

Example

EventBus

This code is taken from [Athen] and is licensed under the BSD-3 clause.

kotlin
object EventBus {
    // A concurrent thread-safe hash map of events and the arrays of nodes associated with that event.
    val all = ConcurrentHashMap<Class<out Event>, Array<Node<out Event>>>()

    fun <T : Event> post(event: T) {
        // Gets the array of Nodes for the event's class
        val nodes = all[event.javaClass] as? Array<Node<T>> ?: return
        for (i in nodes) { // Iterates over each node
            i.handler(event) // Calls the handler for the node with the event
        }
    }

    fun add(node: Node<*>) {
        // A whole bunch of code, but all it does is add the Node to the array of Nodes
    }

    fun remove(node: Node<*>) {
        // A whole bunch of code, but all it does is remove the Node from the array of Nodes
    }
}

Event class

kotlin
abstract class Event {
    var isCancelled = false
        private set

    fun post(): Boolean {
        EventBus.post(this) // Passes the event to the EventBus to be posted
        return isCancelled // Returns whether the event was cancelled
    }

    interface Cancellable {
        fun cancel() {
            (this as Event).isCancelled = true
        }
    }
}

abstract class CancellableEvent : Event(), Event.Cancellable

Extensions

kotlin
/**
 * Extensions for ease of use, gives access to the format:
 * on<Event> {
 *     println(eventVar1)
 * }
 * 
 * on<PacketEvent.Receive, Packet> {
 *     println(packetVar1)
 * }
 */
inline fun <reified T : Event> on(
    priority: Int = 0,
    noinline handler: T.() -> Unit
) = Node(T::class.java, handler, priority).apply { register() }

inline fun <reified E : PacketEvent, reified P : Packet<*>> on(
    priority: Int = 0,
    noinline handler: P.(E) -> Unit
): Node<*> {
    return on<E>(priority) {
        (packet as? P)?.handler(this)
    }
}

Not affiliated with Mojang, Microsoft, or Hypixel.