Last active
July 1, 2022 00:32
-
-
Save austin362667/070954651a406b94736dc18f6c2cb4b4 to your computer and use it in GitHub Desktop.
a tiny functional event emitter / pubsub.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // a tiny functional event emitter / pubsub. | |
| fn Emitter(){ | |
| all := {'*':{}} | |
| return { | |
| // A Dynamic object/Map of event names to registered handler functions. | |
| 'all':all, | |
| // Register an event handler for the given type. | |
| 'on':fn(type, handler){ | |
| (all[type])?push(all[type], handler):set(all, type, handler) | |
| }, | |
| // Invoke all handlers for the given type. | |
| 'emit': fn(type, evt) { | |
| all[type]?map(all[type], fn(handler){ handler(evt) }):{} | |
| // map(all.get('*').slice(), fn(handler){handler(evt)}) | |
| } | |
| } | |
| } | |
| fn set(m, k, v){ | |
| m[k] = v | |
| return m | |
| } | |
| /* | |
| class Emitter { | |
| all | |
| fn __init() { | |
| $all = {} | |
| } | |
| fn all() { | |
| return $all | |
| } | |
| fn on(type, handler) { | |
| handlers := $all[type] | |
| if(handlers!=null) { | |
| push($all[type], handler) | |
| } else { | |
| $all[type] = handler | |
| } | |
| } | |
| fn emit(type, evt){ | |
| handlers := $all[type] | |
| if(handlers) { | |
| map($all[type], fn(handler){ handler(evt) }) | |
| } | |
| } | |
| } | |
| */ | |
| emitter := Emitter() | |
| // listen to an event | |
| emitter.on('foo', fn(e){log('foo', e)}) | |
| // fire an event | |
| emitter.emit('foo', {'a': 'b'}) | |
| // working with handler references: | |
| fn onFoo(e) { log('foo', e) } | |
| emitter.on('foo', onFoo) // listen | |
| // fire an event | |
| emitter.emit('foo', {'a': 'c'}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment