From Web Component to Lit Elements

43 mins remaining
Back Next

6. Adding Functionality

Property Bindings

Currently, the only way to set the rating on the rating-element is to construct the element, set the rating property on the object, and then put it on the page. Unfortunately, this is not how native HTML elements tend to work. Native HTML elements tend to update with both property and attribute changes.

Make the custom element update the view when the rating property changes by adding the following lines:

Code Checkpoint

index.js

You add a setter and getter for the rating property, and then you update the rating element's text if it's available. This means if you were to set the rating property on the element, the view will update; give it a quick test in your Dev Tools console!

Attribute Bindings

Now, update the view when the attribute changes; this is similar to an input updating its view when you set <input value="newValue">. Luckily, the Web Component lifecycle includes the attributeChangedCallback. Update the rating by adding the following lines:

Attribute Bindings

Now, update the view when the attribute changes; this is similar to an input updating its view when you set <input value="newValue">. Luckily, the Web Component lifecycle includes the attributeChangedCallback. Update the rating by adding the following lines:

index.js

In order for the attributeChangedCallback to trigger, you must set a static getter for RatingElement.observedAttributes which defines the attributes to be observed for changes. You then set the rating declaratively in the DOM. Give it a try:

index.html

The rating should now be updating declaratively!

Button Functionality

Now all that's missing is the button functionality. The behavior of this component should allow the user to provide a single up or down vote rating and give visual feedback to the user. You can implement this with some event listeners and a reflecting property, but first update the styles to give visual feedback by appending the following lines:

Congratulations, you now have a fully-featured Web Component; try clicking on some buttons! The issue now is that my JS file is now reaching 96 lines, my HTML file 43 lines, and the code is quite verbose and imperative for such a simple component. This is where Google's Lit project comes in!