Skip to content

Attribute binding

Rafał Lorenz edited this page May 17, 2017 · 3 revisions

We can easy bind attributes for our custom element. By providing array of attr names in a static function observedAttributes. By defining attr name for example who

import { WebComponent } from 'web-component'

@WebComponent('hello-world', {
  template: require('./hello-world.html')
})
export class HelloWorld extends HTMLElement {
  static get observedAttributes() {
    return ['who'];
  }
}

Docorator will handle for us:

  1. What happens is that decorator adds a class property which you can access this._who for example to set a default value in a controller
import { WebComponent } from 'web-component'

@WebComponent('hello-world', {
  template: require('./hello-world.html')
})
export class HelloWorld extends HTMLElement {
  constructor() {
    super();
    this._who = null;
  }
}
  1. Next thing is it watches attributeChangedCallback and whenever attribute who is changed it updates this._who property.
<hello-world who="Unicorn"></hello-world>
  1. It watches connectedCallback and if our custom element has attribute who it updates this._who property

  2. It adds getter and setter methods, this way we can access, and change attr value with ajvascript.

const helloWorldComponent = document.findElementById('example');
helloWorldComponent.who; //display value of this._who
helloWorldComponent.who = 'Unicorn'; //sets attr and this._who property value to Unicorn
Clone this wiki locally