-
Notifications
You must be signed in to change notification settings - Fork 11
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Björn Ritzl
committed
Sep 19, 2017
1 parent
219f7eb
commit f8b5cbf
Showing
1 changed file
with
39 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,39 @@ | ||
local M = {} | ||
|
||
function M.create(signal_id) | ||
assert(signal_id, "You must provide a signal_id") | ||
local signal = {} | ||
|
||
local listeners = {} | ||
|
||
function signal.add(cb) | ||
assert(cb, "You must provide a callback") | ||
if type(cb) == "function" then | ||
listeners[cb] = { fn = cb } | ||
else | ||
local key = hash_to_hex(cb.socket or hash("")) .. hash_to_hex(cb.path or hash("")) .. hash_to_hex(cb.fragment or hash("")) | ||
listeners[key] = { fn = function(message) msg.post(cb, signal_id, message) end } | ||
end | ||
end | ||
|
||
function signal.remove(cb) | ||
assert(cb, "You must provide a callback") | ||
if type(cb) == "function" then | ||
listeners[cb] = nil | ||
else | ||
local key = hash_to_hex(cb.socket or hash("")) .. hash_to_hex(cb.path or hash("")) .. hash_to_hex(cb.fragment or hash("")) | ||
listeners[key] = nil | ||
end | ||
end | ||
|
||
function signal.trigger(message) | ||
assert(message, "You must provide a message") | ||
for k,v in pairs(listeners) do | ||
v.fn(message) | ||
end | ||
end | ||
|
||
return signal | ||
end | ||
|
||
return M |