Skip to content

Instantly share code, notes, and snippets.

@tur-nr
Created October 10, 2015 04:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tur-nr/317184251ebcd3ed289c to your computer and use it in GitHub Desktop.
Save tur-nr/317184251ebcd3ed289c to your computer and use it in GitHub Desktop.
Web Component Lifecycle

Consider the following scenario. I have element foo which has a child element, bar. Now foo will make use of bar in someway, this could be calling a method from bar's prototype or just checking the instance. Due to the nature of a DOM tree structure foo gets lifecycle events first createdCallback and attachedCallback. If you try and reference any child custom elements within those callbacks, they have not be initialised correctly and their prototype is HTMLElement and not of their respected prototypes defined when registering the element. This means that the assertions in foo.js will fail sadly.

In order to use the instance of the element with it's correct prototype, you must allow all lifecycle events for each custom element, including their children, to complete before using the instances of those custom elements.

(function(window) {
var bar = Object.create(HTMLElement.prototype);
bar.createdCallback = function() {
console.log('x-bar created');
};
bar.attachedCallback = function() {
console.log('x-bar attached');
};
window.BarElement = document.registerElement('x-bar', { prototype: bar });
})(this);
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<script src="bar.js"></script>
<script src="foo.js"></script>
</head>
<body>
<x-foo>
<x-bar></x-bar>
</x-foo>
</body>
</html>
(function(window, BarElement) {
var foo = Object.create(HTMLElement.prototype);
foo.createdCallback = function() {
console.log('x-foo created');
// get bar
var bar = this.querySelector('x-bar');
// we expect this to be true, sadly it's not
console.assert(bar instanceof BarElement);
};
foo.attachedCallback = function() {
console.log('x-foo attached');
// get bar
var bar = this.querySelector('x-bar');
// we expect this to be true, sadly it's not
console.assert(bar instanceof BarElement);
};
window.FooElement = document.registerElement('x-foo', { prototype: foo });
})(this, this.BarElement);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment