Needing an event subscription and publishing system for a HTML5/canvas game I’m creating, I wrote a very light event system.
Anything than can call JavaScript (link, button, etc) can raise an event:
LightEvents.publishEvent('event name', data);
Subscribing to events is equally easy:
1 2 3 |
LightEvents.listenFor('event name', function (data) { //callback function }); |
Here is the LightEvents object, demo is embedded below
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
/* LightEvents Michael Jasper - 2013 http://www.mikedoesweb.com/2013/custom-events-system-in-javascript-lightevents/ */ var LightEvents = (function () { this.listeners = []; this.me = this; this.publishEvent = function (e, d) { for (var l in me.listeners) { if (me.listeners[l].event === e) { me.listeners[l].callback(d); } } }; this.listenFor = function (e, c) { this.listeners.push({ event: e, callback: c }); }; return this; })(); |