Skip to content

Instantly share code, notes, and snippets.

@EleotleCram
Last active March 7, 2017 13:23
Show Gist options
  • Save EleotleCram/db385c75cdaec1dc89377ac63624cb0b to your computer and use it in GitHub Desktop.
Save EleotleCram/db385c75cdaec1dc89377ac63624cb0b to your computer and use it in GitHub Desktop.
drop-in synchronous bus gist using jquery-node
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