Skip to content

Instantly share code, notes, and snippets.

@atamocius
Created April 20, 2018 01:23
Show Gist options
  • Save atamocius/d478739ea8ec2548bf5ef190358aae51 to your computer and use it in GitHub Desktop.
Save atamocius/d478739ea8ec2548bf5ef190358aae51 to your computer and use it in GitHub Desktop.
Publish-subscribe pattern implementation in Lua (ported from "Learning JavaScript Design Patterns" book)
-- https://addyosmani.com/resources/essentialjsdesignpatterns/book/#observerpatternjavascript
local M = {}
-- Storage for topics that can be broadcast
-- or listened to
local topics = {}
-- A topic identifier
local sub_uid = 0
-- Publish or broadcast events of interest
-- with a specific topic name and arguments
-- such as the data to pass along
M.publish = function(topic, args)
if not topics[topic] then
return false
end
local subscribers = topics[topic]
local len = subscribers and #subscribers or 0
while len > 0 do
subscribers[len].func(topic, args)
len = len - 1
end
end
-- Subscribe to events of interest
-- with a specific topic name and a
-- callback function, to be executed
-- when the topic/event is observed
M.subscribe = function(topic, func)
if not topics[topic] then
topics[topic] = {}
end
sub_uid = sub_uid + 1
table.insert(topics[topic], {
token = sub_uid,
func = func
})
return sub_uid
end
-- Unsubscribe from a specific
-- topic, based on a tokenized reference
-- to the subscription
M.unsubscribe = function(token)
for k, v in pairs(topics) do
for i = 1, #v do
if v[i].token == token then
table.remove(v, i)
return token
end
end
end
end
return M
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment