Skip to content

EventBus

Source: shiva-fw/libs/eventbus/init.lua

Cross-module Lua-to-Lua event system with priority ordering and before/after method plugin hooks. This is not a FiveM network event bus — it is an in-process signal system.

Availability

EventBus is a global in every shiva module (loaded by sh_init.lua). No import required.

Subscribing

EventBus.on(eventName, handler, priority?)

Subscribe to an event. Lower priority numbers run first (default: 100).

lua
EventBus.on('player:spawned', function(playerId)
    print('Player spawned:', playerId)
end)

EventBus.on('economy:transfer', handler, 10)  -- runs early

EventBus.off(eventName)

Unsubscribe all handlers for an event.

lua
EventBus.off('player:spawned')

Emitting

EventBus.emit(eventName, ...)

Emit an event, passing arbitrary arguments to each handler.

lua
EventBus.emit('player:spawned', playerId)
EventBus.emit('economy:transfer', { from = src, to = dst, amount = 500 })

EventBus.emitWithResponse(eventName, ...)

Emit an event and allow handlers to halt it. Returns allowed (true) and an optional reason string.

A handler can return EventBus.halt(reason) to stop propagation.

lua
local allowed, reason = EventBus.emitWithResponse('inventory:addItem', item)
if not allowed then
    Log.warn('inventory', 'Item blocked: ' .. (reason or ''))
end

EventBus.halt(value)

Sentinel return value used inside emitWithResponse handlers to halt the event.

lua
EventBus.on('inventory:addItem', function(item)
    if item.weight > maxCarryWeight then
        return EventBus.halt('Too heavy')
    end
end)

Method Plugins (Before / After hooks)

EventBus.before(serviceName, methodName, fn, sortOrder?)

Register a function that runs before a service method. Lower sortOrder runs first. The fn receives the same arguments as the original method. Return EventBus.halt(value) to block the call.

lua
EventBus.before('EconomyService', 'addMoney', function(src, amount, reason)
    Log.debug('economy', 'Before addMoney', { src = src, amount = amount })
end)

EventBus.after(serviceName, methodName, fn, sortOrder?)

Register a function that runs after a service method. Receives the return value as its first argument (plus original args). Can modify and return a new value.

lua
EventBus.after('EconomyService', 'addMoney', function(result, src, amount, reason)
    -- result is whatever addMoney returned
    return result
end)

EventBus.wrapWithPlugins(serviceName, methodName, originalFn)

Wrap a function with all registered before/after plugins for a service method. Called automatically by the Container; rarely needed directly.

lua
MyService.addMoney = EventBus.wrapWithPlugins('MyService', 'addMoney', MyService.addMoney)

Utilities

EventBus.reset()

Clear all handlers and plugins (used in tests).

lua
EventBus.reset()

Released under the MIT License.