Page 1 of 1

Small event handling module

Posted: Mon Jul 13, 2015 5:22 am
by airstruck
This module provides a simple way to register multiple handlers for events.

The module has no knowledge of Love's API, so the first step (in main.lua) is this:

Code: Select all

local Event = require 'event'
Event.injectDispatchers(love.handlers)
Event.injectDispatchers(love, { 'load', 'update', 'draw' })
This "hijacks" all standard Love events, as well as the love.load, love.update and love.draw callbacks.

Now instead of defining (for example) love.update, you can do something like this:

Code: Select all

Event.on('update', function (dt)
    myGame:updateStuff(dt)
end)
The benefit here is that you can register as many handlers as you like for this "update" event; all of them will fire.

If you need to unregister an event handler at some point, save the return value from Event.on and call :remove() on it later.

Code: Select all

local keyHandler = Event.on('keypressed', function (b, s, r)
    myGame:mashButtons(b, s, r)
end)
-- later...
keyHandler:remove()
You can also dispatch your own events if you like. These are not Love events, they are produced and consumed within this module.

Code: Select all

Event.dispatch('pebkac', keyboard, chair)
That's pretty much it, do whatever you want with it. Any input on API or implementation is welcome.

https://gist.github.com/airstruck/9c07256b06ef5925c540

Re: Small event handling module

Posted: Mon Jul 13, 2015 5:47 am
by FruityLark
Reminds me of javascript EventListeners or jquery binds. I like it.
Is this common in other languages?

Re: Small event handling module

Posted: Mon Jul 13, 2015 6:01 am
by airstruck
FruityLark wrote:Reminds me of javascript EventListeners or jquery binds. I like it.
Thanks, it's partly inspired by EventListeners and partly by "DOM 0" events (in that you can return false from within a handler to stop other handlers from processing the event, forgot to mention that).
Is this common in other languages?
I think it's very common to have some way of hooking up multiple handlers to events, yeah. I understand why Love doesn't do this by default, keeps things simple and it's easy enough to override the behavior. For anything more than very simple applications it's probably cleaner to have something like this, though.