2016-04-15 11:13:13 +01:00

70 lines
2.3 KiB
HTML

<!-- Defines element markup -->
<template>
<p>Hello <strong></strong> :)</p>
<content></content>
</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 _text = '_text';
var MyElementProto = Object.create(HTMLElement.prototype, {
text: {
get: function() { return _text; },
set: function(newValue) {
_text = newValue;
this.setText(newValue);
}
}
});
// 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 "text" attribute has been overwritten
/*
if (this.hasAttribute('text')) {
var text = this.getAttribute('text');
this.setText(text);
}
else {
this.setText(this.text);
}
*/
};
// Fires when an attribute was added, removed, or updated
MyElementProto.attributeChangedCallback = function(attr, oldVal, newVal) {
if (attr === 'text') {
this.setText(newVal);
}
};
MyElementProto.setText = function(val) {
_text = val;
this.strong.textContent = val;
};
// Registers <hello-world> in the main document
window.MyElement = thatDoc.registerElement('hello-world', {
prototype: MyElementProto
});
})(window, document);
</script>