jj
    Preparing search index...

    Function attr2prop

    • A helper to bridge the attribute world (kebab-case) to the property world (camelCase). It works in tandem with browser's observedAttributes feature which triggers attributeChangedCallback.

      Parameters

      • instance: HTMLElement

        A reference to the common component instance

      • name: string

        kebab-case and in lower case exactly as it appears in observedAttributes.

      • oldValue: any

        The previous value of the attribute.

      • newValue: any

        The new value of the attribute.

      Returns boolean

      true if it tried to set the attribute; otherwise false.

      Your custom component class MUST define static observedAttributes[] otherwise attributeChangedCallback won't trigger. observedAttributes should contain kebab-based attribute names.

      class MyComponent extends HTMLElement {
      static observedAttributes = ['user-name', 'counter']
      userName = '' // Property MUST exist on the instance (or prototype setter)
      #counter = 0 // You can also use private properties together with getter/setters

      attributeChangedCallback(name, oldValue, newValue) {
      attr2prop(this, name, oldValue, newValue)
      }

      get counter() {
      return this.#counter
      }

      set counter(value) {
      this.#counter = value
      this.#render() // You can call your render function to update the DOM
      }

      #render() {
      const shadow = JJHE.from(this).shadow
      if (shadow) {
      shadow.find('#user').setText(this.userName)
      shadow.find('#counter').setText(this.counter)
      }
      }
      }