Lua event emitter/listener implementation. Implementation uses queueing, so it's always ok to emit messages during processing of previous message. The only pitfall you may encounter is that you can actually create deadlock if you recursively emit messages.
In the library there is defined type EventPool
which handles emitting and
binding of listeners.
local pool = EventPool.new()
--or
local pool2 = EventPool()
Creates new EventPool
.
Bind listener
to messages emitable by source
. After source
emits any messages
pool will lookup callbacks from listener
. Returns true
on success and false
+
error on fail. Possible errors are:
EventPool.ERROR_NIL_SOURCE
, ifsource
isnil
EventPool.ERROR_NIL_LISTENER
, iflistener
isnil
EventPool.ERROR_LISTENER_ALREADY_BINDED
, iflistener
is already binded tosource
local src = {}
local list = {}
pool:bind( src, list ) -- now list listens to src
Unbind listener
from source
. Returns true
on success and false
+ error
on fail. Possible errors are:
EventPool.ERROR_NIL_SOURCE
, ifsource
isnil
EventPool.ERROR_NIL_LISTENER
, iflistener
isnil
EventPool.ERROR_LISTENER_NOT_BINDED
, iflistener
is not binded tosource
Emits message
from source
. All binded listeners with field message
will
be notified and according method (message
) will be called with passed varargs.
Function can return:
EventPool.STATUS_PROCESSED
, if events queue was emptyEventPool.STATUS_QUEUED
, if events queue wasn't empty and message was queued
local src = { name = 'src', }
local list1 = { name = 'list1', onMessage = function( self, source, msg )
print( self.name, source.name, msg )
end }
pool:bind( src, list1 )
pool:emit( src, 'onMessage', 42 ) -- will print list1, src, 42
Lower level of emit
(internally emit
is implemented using notify
) this
function directly notifies all listeners without queueing. This is a bit faster,
but in many cases it can lead to very hard to catch bugs. It's better just not
to use this function.