Skip to content

CustomEvent

CustomEvent enables an object to send an event. CustomEvents is the global instance of CustomEvent.

Functions

CustomEvent CustomEvent.New()
Creates a new instance of CustomEvent.
void AddListener(string eventName, function handler)
Adds an event handler for the eventName event.
void RemoveListener(string eventName, function handler)
Removes the event handler from the eventName event.
void Emit(string eventName, ...)
Emits the eventName event with the following arguments.

Code sample

The following code sample registers a handler which deregisters itself and sends an event.

1
2
3
4
5
6
7
8
9
-- The event arguments should match with the event sended.
local function handler(count, content)  
    print("received:", count, content)
    CustomEvents:RemoveListener("count-content-event", handler)
end

CustomEvents:AddListener("count-content-event", handler)
 -- Sends count-content-event two arguments (a number and a string).
CustomEvents:Emit("count-content-event", 42, "the content is boring") 

Here is another code sample of EventHelper.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
local AddListener = EventHelper.AddListener
local RemoveListener = EventHelper.RemoveListener

local function handler(count, content)
    print("received:", count, content)
    -- Use RemoveListener of EventHelper instead
    RemoveListener(CustomEvents, "count-content-event", handler)
end
 -- Use AddListener of EventHelper instead
AddListener(CustomEvents, "count-content-event", handler)   

CustomEvents:Emit("count-content-event", 42, "the content is boring")