Created
February 2, 2022 16:52
-
-
Save tigt/704816cc9778520b6274c079abf4780d to your computer and use it in GitHub Desktop.
Event bus for Marko components
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
/** | |
* 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