Last active
March 7, 2017 13:23
-
-
Save EleotleCram/db385c75cdaec1dc89377ac63624cb0b to your computer and use it in GitHub Desktop.
drop-in synchronous bus gist using jquery-node
This file contains 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
const $ = require('jquery-node'); | |
// Description: drop-in synchronous bus gist using jquery-node | |
// Usage: | |
// | |
// bus.on("foo", (...args) => { | |
// console.log("foo was triggered", args); | |
// }); | |
// bus.subscribe({ | |
// onFoo(...args) {console.log("foo triggered too", args)} | |
// }); | |
// bus.trigger("foo", 1,2,3); | |
// => foo triggered [ 1, 2, 3 ] | |
// => foo triggered too [ 1, 2, 3 ] | |
// | |
const bus = $('<div>'); | |
module.exports = { | |
on(eventName, handler) { | |
bus.on(eventName, (e, args) => handler(...args)); | |
}, | |
off(...args) { | |
bus.off(...args); | |
}, | |
subscribe(objectWithHandlers) { | |
const uncapitalize = (x) => x.charAt(0).toLowerCase() + x.slice(1); | |
Object.keys(objectWithHandlers) | |
.filter((methodName) => methodName.startsWith("on")) | |
.forEach((methodName) => { | |
const eventName = uncapitalize(methodName.replace(/^on/, "")); | |
handler = objectWithHandlers[methodName]; | |
bus.on(eventName, (e, args) => handler(...args)); | |
}) | |
; | |
}, | |
trigger(eventName, ...args) { | |
bus.triggerHandler(eventName, [args]); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment