-
-
Notifications
You must be signed in to change notification settings - Fork 4
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:
- 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;
}
}
- Next thing is it watches
attributeChangedCallback
and whenever attributewho
is changed it updatesthis._who
property.
<hello-world who="Unicorn"></hello-world>
-
It watches
connectedCallback
and if our custom element has attributewho
it updatesthis._who
property -
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