Skip to content

Foundry Events

BawrLabs edited this page Jun 14, 2026 · 5 revisions

Foundry.Events

Part of the Foundry API reference.

New to WoW addons? Start here →

Foundry.Events is a thin bridge over WoW's native frame-event system. It gives an addon one controller that owns a single hidden frame and an event → handler table, so registering, dispatching, and tearing down game events all live in one place, without hiding the native primitive underneath.

This page explains the native event model first, then why a per-consumer controller helps once an addon registers more than a handful of events, then the Foundry.Events API with worked examples, the escape hatch, and finally how to migrate from AceEvent-3.0.

API version: Foundry.Events is API version 1. Assert it with F:RequireModule("Events", 1) if your addon needs the module present at a minimum version. (This is the module's version; the library as a whole is F.API_VERSION.)


1. Game events in WoW: the native primitive

WoW delivers game events to frames. You create a frame, tell it which events you care about, and give it an OnEvent script that runs every time one of those events fires:

local frame = CreateFrame("Frame")
frame:RegisterEvent("PLAYER_LOGIN")
frame:RegisterEvent("BAG_UPDATE_DELAYED")

frame:SetScript("OnEvent", function(self, event, ...)
    -- self  is the frame
    -- event is the event name, e.g. "PLAYER_LOGIN"
    -- ...   is the event's payload, exactly as WoW delivers it
    if event == "PLAYER_LOGIN" then
        -- ...
    elseif event == "BAG_UPDATE_DELAYED" then
        -- ...
    end
end)

The pieces that make this work:

  1. CreateFrame("Frame"): a frame is the only object that receives events. It does not need to be shown or parented to anything to listen.
  2. frame:RegisterEvent("EVENT_NAME"): subscribe the frame to one event. Call it again for each event you want.
  3. OnEvent(self, event, ...): the one script that fires for every registered event on that frame. The first argument is the frame, the second is the event name, and the rest is that event's payload.

There is also a narrower subscription for unit events:

frame:RegisterUnitEvent("UNIT_HEALTH", "player", "target")

RegisterUnitEvent registers an event but filters it to one or two named units, so OnEvent only fires for those units instead of every unit in the game. It is the right call for unit-scoped events like UNIT_HEALTH or UNIT_AURA.

This primitive is current and is not deprecated. It is what every event-driven addon ultimately uses, including AceEvent-3.0. For a single frame listening to one or two events, the native primitive is the right tool and Foundry.Events is unnecessary.


2. Why a controller, and when

A frame's OnEvent is a single script for all of its events, so an addon that listens to several events ends up writing one growing if event == ... elseif event == ... chain. Authors usually react by spreading events across several ad-hoc frames, and then three things tend to rot:

  • Dispatch scatters. Some events are handled in one frame's OnEvent branch, others in another frame's; there is no single place that says "here is everything this addon listens to."
  • Cleanup is manual and easy to miss. To stop listening you have to find the right frame and call UnregisterEvent on it, and "unregister everything this addon set up" means tracking every frame you created.
  • Discoverability suffers. Which events are live, and which function handles each one, is spread across RegisterEvent calls and if/elseif branches in different files.

Foundry.Events keeps the native primitive underneath and adds a small registry on top: one controller owns one shared frame and an event → handler table, so each event maps to exactly one named handler, dispatch happens in one place, and "tear down everything I registered" is a single call. This is the discoverability and cleanup argument, not a claim that raw frames are bad. Raw frames stay the right tool for a one-off listener; reach for a controller once the registry earns its keep.


3. Creating a controller: F.Events:New(owner)

local F = _G.Foundry_1_0
local events = F.Events:New("MyAddon")

:New returns a controller object that you hold. The controller owns one hidden frame (CreateFrame("Frame")) and the event → handler table for this addon. No event is registered on the frame until your first :Register call. Foundry does not attach anything to your addon object; you call methods on the controller explicitly. Foundry favors composition by reference (you hold the controller and call its methods) over mixing methods onto your addon object the way some libraries do.

owner is a single argument:

Argument Type Required Meaning
owner string yes Required identity argument. Must be a non-empty string (an empty or non-string owner is rejected). It is stored on the controller but not otherwise read: it does not name the frame, does not appear in diagnostics, and does not scope :UnregisterAll (teardown is always scoped to the controller instance). Reserved for future diagnostic use.

A controller is independent: two controllers (even for the same owner string) own two different frames and two different handler tables, and tearing one down never touches the other.


4. Registering events

controller:Register(event, handler)

events:Register("PLAYER_LOGIN", function(event, ...)
    MyAddon:OnLogin()
end)

events:Register("BAG_UPDATE_DELAYED", function(event, ...)
    MyAddon:RefreshBags()
end)

:Register subscribes the controller's shared frame to event and stores handler against it. When the event fires, the controller calls your handler.

The handler signature is handler(event, ...). This is the one place a reader coming from raw OnEvent has to adjust: the native frame self is dropped. Your handler's first argument is the event name, and the rest (...) is the native payload exactly as WoW delivers it. If you need the frame itself, reach for it through :GetNativeHandles() (see §8) rather than expecting it as the first argument.

-- raw OnEvent:           function(self, event, ...)   -- self is the frame
-- Foundry.Events handler:        function(event, ...) -- frame self dropped

controller:RegisterUnit(event, handler, unit1 [, unit2])

A thin pass-through to the native frame:RegisterUnitEvent. It behaves exactly like :Register (same (event, ...) handler signature, same one-handler-per- event rule), but the event is filtered to the one or two units you name:

events:RegisterUnit("UNIT_HEALTH", function(event, unit)
    if unit == "player" then MyAddon:UpdateHealth() end
end, "player", "target")

Use it for unit-scoped events so your handler is not woken for every unit in the game. unit1 is required; unit2 is optional.

controller:RegisterOnce(event, handler)

Registers a handler that automatically unregisters itself after its first fire, so it runs exactly once:

events:RegisterOnce("PLAYER_ENTERING_WORLD", function(event, isInitialLogin, isReload)
    MyAddon:FirstFrameSetup()
end)

The unregister happens before your handler is invoked, so the event is already gone by the time your code runs. If your handler re-registers the same event in its own body, that re-registration takes effect normally (the auto-unregister has already completed). After a :RegisterOnce fires, the event slot is free, so you can :Register it again.

One handler per event

A controller holds one handler per event. Calling :Register (or :RegisterUnit) for an event that is already registered on this controller is rejected, and the existing registration is left unchanged. Foundry refuses the operation rather than silently overwriting your first handler. To replace a handler, :Unregister the event first, then register the new one.

If you genuinely need two reactions to the same event, compose them in one handler, or use a second controller (see §4.5). Foundry.Events does not fan one event out to multiple handlers on a single controller.

Validation. :Register and :RegisterUnit reject bad input rather than normalizing it (dev builds raise a Lua error; release builds print a diagnostic and refuse; the call returns nothing either way). event must be a non-empty string; handler must be a function; :RegisterUnit requires unit1. Validation is atomic: a rejected call leaves both the controller's table and the native frame's registration set exactly as they were.

4.5 Patterns for a multi-module addon

Because a controller holds one handler per event, several feature modules that each want the same event (say PLAYER_LOGIN) cannot all :Register it on one shared controller, because the second registration is rejected. Two patterns handle this:

  • One controller per module (recommended). Each feature module makes its own controller (F.Events:New("MyAddon.Vendors"), F.Events:New("MyAddon.Map"), and so on) and owns its own events and cleanup. Each controller owns one small hidden frame, and frames are cheap, so a dozen modules with a dozen controllers is a non-issue. The payoff is isolation: vendors.events:UnregisterAll() tears down exactly that module's events and nothing else.
  • One shared controller, fan out yourself. Keep a single controller, register each event once, and let that one handler call into whichever modules care. Use this when modules must react to a shared event in a guaranteed order, or when you want a single teardown point.

Prefer per-module controllers unless you have a specific reason to centralize. It is the cleaner default and matches how each module already owns its own state.


5. Querying and removing

events:IsRegistered("PLAYER_LOGIN")   -- boolean; no side effects

events:Unregister("BAG_UPDATE_DELAYED")  -- remove one event's handler
events:UnregisterAll()                   -- remove every handler this controller owns
  • :IsRegistered(event) returns whether this controller currently has a handler for event. Called on a controller after :Destroy, it returns nil rather than a boolean, because it refuses like every other post-Destroy call.
  • :Unregister(event) removes the handler and calls the matching native frame:UnregisterEvent(event). It is idempotent: unregistering an event that is not registered is a no-op, not an error. Re-registering an event after unregistering it works.
  • :UnregisterAll() removes every handler this controller owns and calls frame:UnregisterAllEvents(). This is the "stop listening to everything I set up" call: one line, no per-frame bookkeeping.

:Unregister and :UnregisterAll always call the matching native unregister, so the frame's live event set never drifts out of sync with the controller's handler table.


6. Tearing down: controller:Destroy()

events:Destroy()

:Destroy unregisters every event, clears the dispatch table, detaches the OnEvent script and hides the shared frame, and marks the controller destroyed. The frame is not destroyed (WoW frames persist); a destroyed controller simply stops listening. Call it when you want deterministic teardown (for example when disabling a feature module); otherwise normal Lua object lifetime handles it once you drop your reference.

After :Destroy, further calls on the controller are rejected (dev builds raise, release builds refuse), so a destroyed controller can never quietly half-work.


7. A worked example: a feature you can toggle

A controller's register/unregister pair is exactly what a feature with an on/off switch wants: it registers its events when enabled and drops them when disabled, without leaving a frame listening in the background:

local F = _G.Foundry_1_0

local Scanner = {}
Scanner.events = F.Events:New("MyScanner")

function Scanner:SetEnabled(enabled)
    if enabled then
        self.events:Register("LFG_LIST_SEARCH_RESULTS_RECEIVED", function(event, ...)
            self:OnResults(...)
        end)
        self.events:Register("LFG_LIST_AVAILABILITY_UPDATE", function(event, ...)
            self:OnAvailability(...)
        end)
    else
        self.events:UnregisterAll()
    end
end

Toggling repeatedly is safe: :UnregisterAll clears the live set, and the next :Register calls re-subscribe from a clean slate.


8. The escape hatch: controller:GetNativeHandles()

When you need to do something Foundry.Events does not wrap, drop to the raw Blizzard surface without removing the controller. GetNativeHandles returns the native objects this controller owns:

local handles = events:GetNativeHandles()
-- handles.frame    == the shared CreateFrame("Frame") this controller owns
-- handles.handlers == a shallow copy (read-only snapshot) of event -> handler

The handlers table is a snapshot, not the live dispatch table: reading or mutating it cannot corrupt dispatch. The frame, by contrast, is the live frame: calling frame:RegisterEvent(...) on it directly does change what fires, which is the intended escape-hatch behavior.

Use this when you need the actual frame: to set an additional script on it, to hand it to a Blizzard API that expects a frame, or to read exactly which events are live. You own the controller and the native handles together; reaching for the handles does not detach the controller. Called on a controller after :Destroy, :GetNativeHandles returns nil rather than a table, because it refuses like every other post-Destroy call.


9. Migrating from AceEvent-3.0

Scope: this covers AceEvent's event registration only. AceEvent-3.0 also provides a message bus (RegisterMessage / SendMessage / UnregisterMessage) for inter-module communication. Foundry.Events does not replace that (see §10). If your addon uses AceEvent messages, keep AceEvent for them, use CallbackHandler-1.0 directly, or roll your own dispatcher; migrating your events here does not migrate your messages.

AceEvent mixes RegisterEvent onto your addon object and routes each event either to a method named by string or to a closure you pass inline. Both forms appear in real addons; both migrate the same way, into explicit controller:Register calls.

The method-name handler form

AceEvent lets you name a handler method as a string, and it looks that method up on your addon object when the event fires (passing self, the event name, and the payload). Foundry.Events does not look methods up for you; you bind the method yourself in a closure, which is also where the dropped frame self is accounted for.

Before (AceEvent-3.0, method-name form):

-- "AceEvent-3.0" is mixed into the addon via AceAddon's NewAddon
function MyAddon:OnEnable()
    self:RegisterEvent("PLAYER_LOGIN", "OnLogin")
    self:RegisterEvent("BAG_UPDATE_DELAYED", "OnBagUpdate")
end

function MyAddon:OnLogin(event, ...)        self:DoLogin() end
function MyAddon:OnBagUpdate(event, ...)    self:RefreshBags() end

After (Foundry.Events):

local F = _G.Foundry_1_0

function MyAddon:OnEnable()
    local events = F.Events:New("MyAddon")
    events:Register("PLAYER_LOGIN",       function(event, ...) self:OnLogin(...) end)
    events:Register("BAG_UPDATE_DELAYED", function(event, ...) self:OnBagUpdate(...) end)
    self.events = events  -- hold the controller
end

function MyAddon:OnLogin(...)        self:DoLogin() end
function MyAddon:OnBagUpdate(...)    self:RefreshBags() end

The closure function(event, ...) self:OnLogin(...) end does two jobs at once: it binds the method to the correct self (the addon object, since AceEvent used to supply it), and it absorbs the dropped frame self by giving the handler the (event, ...) signature Foundry delivers. Your method keeps whatever signature you want behind the closure.

The closure handler form

AceEvent also accepts an inline function instead of a method name. This migrates almost verbatim: the only change is the handler signature.

Before (AceEvent-3.0, closure form):

self:RegisterEvent("MERCHANT_SHOW", function(event, ...)
    MyAddon:OnMerchantShow()
end)

After (Foundry.Events):

events:Register("MERCHANT_SHOW", function(event, ...)
    MyAddon:OnMerchantShow()
end)

Tearing everything down

AceEvent's "stop listening to everything" call maps one-to-one:

-- Before (AceEvent-3.0):
function MyAddon:OnDisable()
    self:UnregisterAllEvents()
end

-- After (Foundry.Events):
function MyAddon:OnDisable()
    self.events:UnregisterAll()
end

What changed, and why it is the point

  • Event registration is now on a plain controller you hold (self.events), not mixed onto your addon object by a library you cannot see from the call site. Which events are live, and which handler runs each one, is all in one place.
  • The handler signature is (event, ...): the native frame self is dropped. AceEvent's method-name form is replaced by a one-line closure that binds your self and accounts for the dropped argument.
  • "Unregister everything" is :UnregisterAll(), scoped to exactly the events this controller owns.

One behavior worth carrying into a migration: a single controller holds one handler per event. If your addon registered the same event from two places and relied on the last registration winning, that ambiguity surfaces during migration as a rejected duplicate registration. Resolve it deliberately (combine the two reactions into one handler, or give the second one its own controller, §4.5) rather than relying on last-write-wins.


10. What Foundry.Events does not do

  • It does not provide a messaging or callback bus. There is no SendMessage/RegisterMessage equivalent for inter-module communication; that stays your addon's own concern (see the scope note in §9).
  • It does not filter chat messages. Chat-message filtering is a separate Blizzard API and is out of scope.
  • It does not throttle, coalesce, debounce, or bucket event delivery. Each registered event calls your handler every time it fires; rate control is the consumer's responsibility.
  • It does not fan one event out to multiple handlers on a single controller. One handler per event; compose fan-out yourself or use multiple controllers (§4.5).
  • It does not silently attach methods onto your addon object. The controller is a plain, mixin-able object; Foundry never mixes it in for you.
  • It does not persist any state. Registrations are runtime only; there are no SavedVariables.

Clone this wiki locally