Event system
This is a wrapper for our emitter that allows us to emit custom events in a standardized way.
We use custom events to trigger library import / intantiation in determinate situations:
- When we use an anchor to and we need to instantiate the height modifying libraries before going to the destination
- When we need to trigger a library inside another library, for instance, a slider inside a collapsify tab, or a form inside a modal
This wrapper helps us use these events with standardized naming and some safety checks.
Main methods
Section titled “Main methods” loadEvent = ({ library, where, options }) => { this.#checkParams(library, where); this.debug.events(`Event ${library}:load fired from ${where}`); this.emitter.emit(`${library}:load`, options); };
destroyEvent = ({ library, where, options }) => { this.#checkParams(library, where); this.debug.events(`Event ${library}:destroy fired from ${where}`, {color: 'red'}); this.emitter.emit(`${library}:destroy`, options); };We have methods to create both load and destroy events.
These methods will first perform the safety checks via our helper method checkParams() and then emit an event with a naming convention that consists of the library name and the keyword for what the event is intended to be used for.
So if we want to load a Slider inside one of our modals, in our Modal handler we would call:
eventSystem.loadEvent({ library: "Slider", where: 'Modal' });And we would end up with an event called “Slider:load” that comes from the “Modal” library.
We use the origin where parameter for debug purposes.
Helper methods
Section titled “Helper methods” #checkParams(library, where) { if (!this.availableLibraries.includes(library)) { this.debug.error(`⛔️ Library ${library} not allowed`); throw new Error(`⛔️ Library ${library} not allowed`); }
if(!where){ this.debug.error(`⛔️ Pass "where" parameter`) throw new Error(`⛔️ Pass "where" parameter`); } }
#getAvailableLibraries() { const modules = getModules(); this.availableLibraries = []; modules.map((mod) => this.availableLibraries.push(mod.name)); }checkParams() is in charge of performing those safety checks mentioned above.
It will check that our library name matches any of our available libraries exactly using the getAvailableLibraries() method, because if it doesn’t, then the event won’t be listened properly.
It will also check that we have passed a where parameter, so our debugger can function correctly.
Knowledge Check
Test your understanding of this section
Loading questions...
