This repository has been archived by the owner on Dec 29, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 38
/
hello-world.html
65 lines (52 loc) · 1.95 KB
/
hello-world.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
<!-- Defines element markup -->
<template>
<p>Hello <strong></strong> :)</p>
</template>
<script>
(function(window, document, undefined) {
// Refers to the "importer", which is index.html
var thatDoc = document;
// Refers to the "importee", which is src/hello-world.html
var thisDoc = (thatDoc._currentScript || thatDoc.currentScript).ownerDocument;
// Gets content from <template>
var template = thisDoc.querySelector('template').content;
// Creates an object based in the HTML Element prototype
var MyElementProto = Object.create(HTMLElement.prototype);
// Creates the "who" attribute and sets a default value
MyElementProto.who = 'World';
// Fires when an instance of the element is created
MyElementProto.createdCallback = function() {
// Creates the shadow root
var shadowRoot = this.createShadowRoot();
// Adds a template clone into shadow root
var clone = thatDoc.importNode(template, true);
shadowRoot.appendChild(clone);
// Caches <strong> DOM query
this.strong = shadowRoot.querySelector('strong');
// Checks if the "who" attribute has been overwritten
if (this.hasAttribute('who')) {
var who = this.getAttribute('who');
this.setWho(who);
}
else {
this.setWho(this.who);
}
};
// Fires when an attribute was added, removed, or updated
MyElementProto.attributeChangedCallback = function(attr, oldVal, newVal) {
if (attr === 'who') {
this.setWho(newVal);
}
};
// Sets new value to "who" attribute
MyElementProto.setWho = function(val) {
this.who = val;
// Sets "who" value into <strong>
this.strong.textContent = this.who;
};
// Registers <hello-world> in the main document
window.MyElement = thatDoc.registerElement('hello-world', {
prototype: MyElementProto
});
})(window, document);
</script>