Last active
January 20, 2020 19:25
-
-
Save nmquebb/5dd0ecd0521d5c07c4f83c6b796f3fc5 to your computer and use it in GitHub Desktop.
Simple Components
This file contains hidden or 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
| import { Slider } from "./components/Slider"; | |
| import { Modal } from "./components/Modal"; | |
| // Store all of the components in an object we can reference. | |
| const REGISTERED_COMPONENTS = { | |
| Slider, | |
| Modal, | |
| } | |
| function init() { | |
| // Grab every element that has a `data-component` declared | |
| const pageComponents = Array.from(document.querySelectorAll("[data-component]")) | |
| // If we have components on the page, iterate and instantiate. | |
| if (pageComponents.length) { | |
| let index = 0, length = pageComponents.length, el; | |
| for (; index < length; index++) { | |
| // Get the specific element with the `data-component` attr. | |
| el = pageComponents[index] | |
| // Store the result of trying to grab the component from our | |
| /// registered components object. | |
| const Component = REGISTERED_COMPONENTS[el.dataset.component] | |
| // If there is a typo or something it'd be undefined so just | |
| // check before trying to instantiate. When we do kick the tires | |
| // pass in the el that has the data attr on it. | |
| if (Component) new Component(el) | |
| else console.warn(`Failed to create component ${el.dataset.component}. Verify it exists.`) | |
| } | |
| } | |
| } | |
| document.addEventListener("DOMContentLoaded", init); | |
This file contains hidden or 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
| <ul data-component="Slider">...</ul> | |
| <div data-component="Modal">...</div> | |
| <div data-component="DoesntExist">...</div> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment