Events in julia
using Pkg; Pkg.add("EventEmitter")
All code licensed under the MIT license.
First run
using EventEmitter
Construct an Event
myevent = Event()
You can pass callback functions as arguments
myfunction() = println("function")
myevent = Event(myfunction, () -> println("Arrow function"))
Listeners are on
by default. change this by setting once
myevent = Event((x) -> print(x); once=true)
Or construct listeners manually and pass them
# Listener(callback, once)
myevent = Event(Listener(() -> 1), Listener(() -> 2, true))
Use on!()
or once!()
to add listeners
on!(myevent) do
return "called everytime"
end
once!(myevent) do
return "called once"
end
Emit an event by calling it or using emit!()
myevent() # [1, 2, "called everytime", "called once"]
emit!(myevent) # [1, "called everytime"]
Listeners are called in order
myevent = Event(() -> 1, () -> 2)
on!(myevent, () -> 3)
myevent() # [1, 2, 3]
Use prependlisteners!()
to prepend listeners
prependlisteners!(myevent, () -> 4, () -> 5)
myevent() # [4, 5, 1, 2, 3]
Use off!()
to remove a Listener
*off!()
returns the Listener
it removes, so doing off!(event)()
will call it*
off!(myevent)() # 3 - (last) equivalent to `off!(myevent, 0)()`
off!(myevent, 1)() # 4 - (first)
off!(myevent, -1)() # 1 - (before last)
myevent() # [5, 2]
Construct collections of Event
s (arrays, tuples, named tuples and dictionaries)
event1 = Event(() -> 1)
event2 = Event(() -> 2)
arr = [event1, event2]
tuple = (event1, event2)
namedtuple = (a=event1, b=event2)
dict = Dict(:a => event1, :b => event2)
Emit the collections
*emitting a dict will give almost random order for the events*
emit!(arr) # [[1], [2]]
emit!(tuple) # [[1], [2]]
emit!(namedtuple) # [[1], [2]]
emit!(dict) # [[1], [2]]