Skip to content

Instantly share code, notes, and snippets.

@nmquebb
Last active January 20, 2020 19:25
Show Gist options
  • Select an option

  • Save nmquebb/5dd0ecd0521d5c07c4f83c6b796f3fc5 to your computer and use it in GitHub Desktop.

Select an option

Save nmquebb/5dd0ecd0521d5c07c4f83c6b796f3fc5 to your computer and use it in GitHub Desktop.
Simple Components
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);
<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