Skip to content

Instantly share code, notes, and snippets.

@tigt
Created February 2, 2022 16:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tigt/704816cc9778520b6274c079abf4780d to your computer and use it in GitHub Desktop.
Save tigt/704816cc9778520b6274c079abf4780d to your computer and use it in GitHub Desktop.
Event bus for Marko components
/**
* Connect to the event bus. Call in onMount().
* @param {Component} self Pass in `this` from Marko.
* @param {string} event The name of the event to listen on.
* @param {function} fn What to do when the event fires. Takes the data from bus as an argument,
* and `this` is correctly set. (Arrow functions work if you make them in the `class` section.)
*/
export function subscribe (self, event, fn) {
self.subscribeTo(window).on(`bus:${event}`, e => {
fn.call(self, e.detail)
})
}
/**
* Send an event to the bus.
* @param {string} event The event to fire.
* @param {Object} data The data to pass along.
*/
export function dispatch (event, data) {
window.dispatchEvent(new window.CustomEvent(`bus:${event}`, { detail: data }))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment