Chapter 3. Making your component reusable
This chapter covers
- Using getters and setters to work with data in your component
- Using attributeChangedCallback to listen for attribute changes
- Identifying which attributes to listen for changes on using observedAttributes
- Working with attributes using hasAttribute() getAttribute(), and setAttribute()
In the last chapter, we talked in great depth about simple ways to create your first Web Component. Specifically, we looked at creating your own custom element and assigning some minimal custom logic so your component acts a certain way. But what if you want your component to act differently depending on what parameters you use to set it up? What if you want your component to be adaptable? Usually, the goal in any platform, language, or framework is to create reusable code that can be simply configured to match the widest range of use cases.
Of course, saying we want to create reusable and configurable Web Components is one thing. It’s almost meaningless unless we can talk about a concrete example!
One of my recent interests is 3D on the web. I’m especially interested in how virtual reality (VR) and augmented reality (AR) are making their way into browsers. Delving into WebGL and Three.js or Babylon is a bit too much to get into here (and off-subject), but we can do something simple to demonstrate reusable and configurable components.