Super basic event emitter written for crystal-lang.
Add this to your application's shard.yml
:
dependencies:
events:
github: kcreate/events
branch: master
Just include the module inside any classes you want to have access to the event methods
require "events"
# Some class
class Person
include Events
def initialize
add_event "fart"
end
def fart
invoke_event "fart"
end
end
leonard = Person.new
leonard.on "fart", do
puts "daaamn"
end
leonard.fart
You should see "daaamn" pop up in your console
The test suite has all the examples you need. I usually forget to update the README so just look there.
You first need a class that will emit some events. Add the module to your class like this:
class Person
include Events
end
You should add all your events inside your initialize function to prevent unexpected behaviour. Use add_event for this.
class Person
include Events
def initialize
add_event "wakeup"
add_event "sleep"
end
def wakeup
invoke_event "wakeup"
end
def gotosleep
invoke_event "sleep"
end
# ... The rest of your class
end
Similarly you can remove an event using remove_event. I don't know why you'd want to remove an event, but you can.
class Person
include Events
def initialize
add_event "wakeup"
add_event "sleep"
end
def wakeup
invoke_event "wakeup"
end
def gotosleep
# This first invokes the event and deletes it afterwards
invoke_event "sleep"
remove_event "sleep"
end
end
You can subscribe to these events from the outside like this:
class Person
...
end
leonard = Person.new
leonard.on "wakeup" do
puts "leonard woke up"
end
leonard.on "sleep" do
puts "leonard went to sleep"
end
If you now call the wakeup and gotosleep functions,
leonard.gotosleep
leonard.wakeup
This will be the output in your console
leonard went to sleep
leonard woke up
Calling the on function will add your handler to the event, but also return a proc that removes the handler from the event again. This means you can do stuff like this:
sleephandler = leonard.on "sleep" do
puts "going to sleep"
end
leonard.gotosleep # going to sleep
leonard.gotosleep # going to sleep
sleephandler.call # removing the handler
leonard.gotosleep # ... nothing will be printed
Run crystal spec
to run the test suite.
- Allow passing arguments to callbacks
- Allow the usage of subclasses of
Event
- Add docs to a public website
- Fork it ( https://github.com/kcreate/events/fork )
- Create your feature branch (git checkout -b my-new-feature)
- Commit your changes (git commit -am 'Add some feature')
- Make sure your changes don't break anything (crystal spec)
- Push to the branch (git push origin my-new-feature)
- Create a new Pull Request
- kcreate Leonard Schuetz - creator, maintainer