Going Generic
Let's make our code more generic in this lesson.
As written, our code is almost able to deal with more general cases, but not quite. There are three different elements of the class that are set statically, but we want to change them to make the class more generic.
We need to identify the item to be clicked and the item to be made visible. Our existing class also can only do one other thing in response to the click—it changes the text inside the button. So we’ll want some kind of callback to be executed on each click where we can add arbitrary behavior.
Here’s what I’ve got—again, there are a few different ways to do this, and the fact that I wrote the code this way doesn’t mean that there aren’t other perfectly valid ways:
export default class GenericToggle {toggleButtons: NodeListOf<HTMLElement>targets: NodeListOf<HTMLElement>hidden: booleanconstructor(private parent: Element | Document,private buttonSelector: string,private targetSelector: string,private onToggle?: (button: HTMLElement,target: HTMLElement,state: boolean) => void) {this.toggleButtons = parent.querySelectorAll(this.buttonSelector)this.targets = parent.querySelectorAll(this.targetSelector)this.hidden = this.targets[0].classList.contains("is-hidden")}initHandlers(): void {this.onFilterButtonClick()}onFilterButtonClick(): void {this.toggleButtons.forEach((toggleElement) => {toggleElement.addEventListener("click", () => {this.hidden = !this.hiddenthis.targets.forEach((target) => {target.classList.toggle("is-hidden", this.hidden)if (this.onToggle) {this.onToggle(toggleElement, target, this.hidden)}})})})}}
The default export
keywords
I’ve moved the class to its own file, we’ll also see how to use it after we look at the class itself.
The first thing you might notice as you read the code is that the class definition is now preceded by export default
. We’re creating a module in this file that can be loaded in to other code using import
. Any item in this file that we declare with the keyword export
is exposed to the code that imports this file.
Only the default
class is visible when the module is imported using the import <NAME> from
...