Search code examples
web-componentcustom-element

observedAttributes() is not a function


I have attributes in a JS Custom Element

  static get observedAttributes() {
    return ['state','color'];
  }

How can I get that whole array in the Callback functions of a Custom Element?

this.observedAttributes() is not a function

I must be overlooking something easy...

Update after question in comment:

I kept forgetting Getter and Setters

I can now do this in the constructor():

    this.constructor.observedAttributes.map(attribute => 
    Object.defineProperty(this, attribute, {
      get() {
        return obj.getAttribute(attribute);
      },
      set(newValue) {
        obj.setAttribute(attribute, newValue);
      },
      enumerable: true,//default:false
      configurable: true // default:false
      //writable: true // not valid, since there is a set method!
    }));

(don't care about the memory consumption side effects)


Solution

  • observedAttributes is defined as static so it'll be called off of the class, not an instance. observedAttributes is also a getter (get) so you will not execute it with (). If you defined the custom element class as FancyButton you should use FancyButton.observedAttributes.