object: Add a signal example

This commit is contained in:
Emmanuel Lepage Vallee 2016-05-17 00:59:48 -04:00
parent 08df8fbf03
commit f810d78e7b
2 changed files with 31 additions and 0 deletions

View file

@ -39,6 +39,8 @@ local function find_signal(obj, name, error_msg)
end
--- Add a signal to an object. All signals must be added before they can be used.
--
--@DOC_text_gears_object_signal_EXAMPLE@
-- @tparam string name The name of the new signal.
function object:add_signal(name)
check(self)
@ -54,6 +56,7 @@ end
--- Connect to a signal.
-- @tparam string name The name of the signal
-- @tparam function func The callback to call when the signal is emitted
-- @see add_signal
function object:connect_signal(name, func)
assert(type(func) == "function", "callback must be a function, got: " .. type(func))
local sig = find_signal(self, name, "connect to")
@ -105,6 +108,7 @@ end
--- Disonnect to a signal.
-- @tparam string name The name of the signal
-- @tparam function func The callback that should be disconnected
-- @see add_signal
function object:disconnect_signal(name, func)
local sig = find_signal(self, name, "disconnect from")
sig.weak[func] = nil

View file

@ -0,0 +1,27 @@
local gears = require("gears") --DOC_HIDE
local o = gears.object{}
-- Add a new signals to the object. This is used to catch typos
o:add_signal "my_signal"
-- Function can be attached to signals
local function slot(obj, a, b, c)
print("In slot", obj, a, b, c)
end
o:connect_signal("my_signal", slot)
-- Emit can be done without argument. In that case, the object will be
-- implicitly added as an argument.
o:emit_signal "my_signal"
-- It is also possible to add as many random arguments are required.
o:emit_signal("my_signal", "foo", "bar", 42)
-- Finally, to allow the object to be garbage collected (the memory freed), it
-- is necessary to disconnect the signal or use `weak_connect_signal`
o:disconnect_signal("my_signal", slot)
-- This time, the `slot` wont be called as it is no longer connected.
o:emit_signal "my_signal"