Monday, October 19, 2015

Web Components lifecycle methods 2:attributeChangedCallback

The Web Component callback attributeChangedCallback seems simple enough. Whenever an attribute of your custoim component is changed, it will be called. The purpose of it is to support dynamic use cases: the web site developer can use standard HTML setAttribute to change attributes for your component, and the callback gives you a chance to react on the changes. Without it, or without an implementation of it, your component will not handle changes. But how does it actually work:

Case 1: modify a custom attribute

The first case is pretty straightforward: we have a custom component that defines some custom attributes. I use my own upper88-wordcloud throughout. It defines a couple of custom attributes, rows and options. When they are updated the callback is called, and I simply rerender the component. I use this in the demo page  with this little code snippet:

window.setInterval(function() {
  var chart = document.getElementById('hello_cloud');
  if (chart) {
   chart.setAttribute('rows', JSON.stringify([
    ['Hello', getRandomValue()],
    ['Word', getRandomValue()],
    ['Cloud', getRandomValue()]
   ], null, 2));
 }, 3000);

As expected this leads to that the component is rerendered with modified data every 3 seconds. Note also that this is a callback: it is called after the attribute has been changed, so you can use the getAttribute method and you will get the new value. Also if you check in the attributes property you will get the new value. So far so good.

Case 2: modify standard attribute

My custom element extends HTMLelement and has of course the standard HTML attributes, like title. It also has the standard support for data-xxx attributes, which will be saved in the dataset property. Are they also covered by the callback??

To try this I added the following to the function above:

    chart.setAttribute('title','New title'+getRandomValue());

And yes, this also works, and in the same way. The callback is called after the attribute has been updated, so you can use this also in your component.

Case 3: modify standard properties

Now using setAttribute to modify titles works but its a bit complicated. The title is available as a property, and can be modified directly, like this:

chart.title = 'New title'+getRandomValue();

(I use the helper function getRandomValue() to make sure I actually update the value) And yes, this works too. So it seems we can use the callback to monitor changes, it covers changes not made with setAttribute also.


The attributeChangedCallback helps you develop WebComponents that support dynamic changes.  Developers using your component can dynamically modify component instan ces using standard javascript techniques like setAttribute. You can use the callback to monitor changes not only in your custom attributesbut also in standard HTML attributes.

No comments: