Quite a common desire is to allow code to be notified when a particular event happens elsewhere in the code. This library abstracts that design pattern.
-- Step 1: Create the events object (happens just once) local events = require "util.events"; local myevents = events.new(); -- Step 2: A watcher adds a handler to know when we are poked local function on_poke(data) print("Oh no, I was poked by "..data.."!"); end myevents.add_handler("poked", on_poke); -- Step 3: A poker pokes... passing some data to the handlers myevents.fire_event("poked", "a vicious poker");
This simple example demonstrates the 3 primary ways of interacting with an events object, below follows a reference to each of the methods.
Returns a new events object. This object supports methods for adding handlers for, and firing, events.
These methods exist on objects returned by the above events.new().
Fire the event with the given name, passing the optional data to all handlers.
Should any callback for an event return a value other than nil then fire_event() will stop calling further callbacks return this value.
When the event specified by 'name' is fired the function specified by 'callback' will be called.
Callbacks are called in an unspecified order, except that callbacks with a higher 'priority' are executed first. If not given, the priority defaults to 0.
A callback should return nothing, or nil, to continue processing of other callbacks. Should it return any other value then further callbacks shall not be called, and the value will be returned to the code that fired the event.
Remove the given handler for the specified event. It shall no longer be called when the event is fired.