Skip to content

Instantly share code, notes, and snippets.

@lzubiaur
Last active March 24, 2018 12:34
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save lzubiaur/9017070 to your computer and use it in GitHub Desktop.
Save lzubiaur/9017070 to your computer and use it in GitHub Desktop.
Lua Notification Center (cocos2dx)
--[[
Why this package?
Cocos2d-x CCNotificationCenter is limited to one lua function callback (observer) per target (CCObject).
This simple Lua script wraps CCNotificationCenter and allows code like:
addObserver(foo,'eventname')
addObserver(foo2,'eventname')
]]--
-- The NotificationCenter (nc) table
local nc = {
observers = {},
center = CCNotificationCenter:sharedNotificationCenter(),
obj = CCNode:create() -- Can't use a CCObject because no constructor available in lua (e.g. CCObject:new or CCObject:create())
}
nc.__index = nc
function nc:post(event)
-- Post a nil event will crash
if event then
self.center:postNotification(event)
end
end
function nc:observerExists(func,event)
for k,v in ipairs(self.observers[event]) do
if func == v then
return k
end
end
return nil
end
function nc:removeObserver(func,event)
local i = self:observerExists(func,event)
if i then
table.remove(self.observers[event],i)
end
end
function nc:addObserver(func,event)
if self.observers[event] then
if not self:observerExists(func,event) then
table.insert(self.observers[event],func)
end
else
local a = {}
table.insert(a,func)
self.observers[event] = a
local function notifyScript(event)
for k,v in ipairs(self.observers[event]) do
v()
end
end
self.center:registerScriptObserver(self.obj,notifyScript,event)
end
end
function nc:removeAllObservers()
self.center:removeAllObservers(self.obj)
end
function nc:runTests()
local function foo1()
print 'foo1'
end
local function foo2()
print 'foo2'
end
local event = 'event_foo'
-- Add two observers of the same event
self:addObserver(foo1,event)
self:addObserver(foo2,event)
-- Post an notification. Should print two lines ('foo1', 'foo2')
self:post(event)
-- Add an existing observer
self:addObserver(foo1,event)
-- Remove an observer
self:removeObserver(foo1,event)
-- Post an notification. Should only print one line ('foo2')
self:post(event)
self:removeAllObservers()
end
nc:runTests()
-- Return package table
return nc
@cool8jay
Copy link

cool8jay commented May 2, 2014

  1. line 27, "exists" is not used, I suggest remove it.
  2. line 47, "a" is global, I suggest prefix it with 'local'.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment