|
| 1 | +Element-defined content |
| 2 | + |
| 3 | +Custom elements can manage their own content by using the DOM APIs inside element code. Reactions come in handy for this. |
| 4 | + |
| 5 | +Example - create an element with some default HTML: |
| 6 | + |
| 7 | + customElements.define('x-foo-with-markup', class extends HTMLElement { |
| 8 | + connectedCallback() { |
| 9 | + this.innerHTML = "<b>I'm an x-foo-with-markup!</b>"; |
| 10 | + } |
| 11 | + ... |
| 12 | + }); |
| 13 | + |
| 14 | +Declaring this tag will produce: |
| 15 | + |
| 16 | + <x-foo-with-markup> |
| 17 | + <b>I'm an x-foo-with-markup!</b> |
| 18 | + </x-foo-with-markup> |
| 19 | + |
| 20 | + |
| 21 | + |
| 22 | + |
| 23 | +defining the DOM interface of <app-drawer>: |
| 24 | + |
| 25 | + class AppDrawer extends HTMLElement { |
| 26 | + |
| 27 | + // A getter/setter for an open property. |
| 28 | + get open() { |
| 29 | + return this.hasAttribute('open'); |
| 30 | + } |
| 31 | + |
| 32 | + set open(val) { |
| 33 | + // Reflect the value of the open property as an HTML attribute. |
| 34 | + if (val) { |
| 35 | + this.setAttribute('open', ''); |
| 36 | + } else { |
| 37 | + this.removeAttribute('open'); |
| 38 | + } |
| 39 | + this.toggleDrawer(); |
| 40 | + } |
| 41 | + |
| 42 | + // A getter/setter for a disabled property. |
| 43 | + get disabled() { |
| 44 | + return this.hasAttribute('disabled'); |
| 45 | + } |
| 46 | + |
| 47 | + set disabled(val) { |
| 48 | + // Reflect the value of the disabled property as an HTML attribute. |
| 49 | + if (val) { |
| 50 | + this.setAttribute('disabled', ''); |
| 51 | + } else { |
| 52 | + this.removeAttribute('disabled'); |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | + // Can define constructor arguments if you wish. |
| 57 | + constructor() { |
| 58 | + // If you define a constructor, always call super() first! |
| 59 | + // This is specific to CE and required by the spec. |
| 60 | + super(); |
| 61 | + |
| 62 | + // Setup a click listener on <app-drawer> itself. |
| 63 | + this.addEventListener('click', e => { |
| 64 | + // Don't toggle the drawer if it's disabled. |
| 65 | + if (this.disabled) { |
| 66 | + return; |
| 67 | + } |
| 68 | + this.toggleDrawer(); |
| 69 | + }); |
| 70 | + } |
| 71 | + |
| 72 | + toggleDrawer() { |
| 73 | + ... |
| 74 | + } |
| 75 | + } |
| 76 | + |
| 77 | + customElements.define('app-drawer', AppDrawer); |
0 commit comments