Home > database >  What's the difference between using observedAttributes() vs MutationObserver
What's the difference between using observedAttributes() vs MutationObserver

Time:07-03

With a custom component, you can use the static get observedAttributes() in your web component to specify what attribute changes trigger the attributeChangedCallback() lifecycle method.

However, it seems you can also achieve a similar callback by using the MutationObserver API, documented here, with {attributes: true} to watch all attribute changes, or to refine it more, using a {attributeFilter: Array<string>}.

What's the difference in using the two different methods? Seems like the MutationObserver offer much more flexibility, while the first method is equivalent to having defined an attribute filter.

CodePudding user response:

Yes, minor functional differences.

But MutationObserver takes a lot more boilerplate, and you can't ask the MO which attributes are observed.

It is kinda like saying Why do we need Map, when everything can be done by extending Array

I don't have data, but would say observedAttributes is highly optimized. MO is taking a sledgehammer to drive in a nail.

But as you commented; observedAttributes doesn't give you dynamic attributes.

  • Related