Custom Elements play an important role in Web Components spectrum. Here’s a list that talks about why we need them:
Define new DOM elements.
Extending from other elements.
Extending DOM APIs.
Providing custom functionality to a single tag.
A custom element is made up of a local name, namespace, prototype and lifecyle callbacks.
After creating the custom element, the element definition is added to a registry using the document.registerElement()
method. The lifecycle of a custom element is listed below:
Custom element is created before its definition is registered.
Definition of a custom element is registered.
Custom element instance is created after its definition was registered.
Custom element is inserted into active document.
Custom element is removed from active document.
Custom element’s attribute is created, removed, or modified.
Creating custom element with ES6
is easy using it's class
feature, but it's important to note that the only subclassing that works is of your own classes, we can't subclass builtins or platform objects, the issues are about allocation of the object (especially for DOM objects), about passing arguments to the superconstructor (arbitrary arguments) --- DOM objects don't really have callable constructors right now, so until the DOM catches up with ES6 specs we need to deal with these limitations.
Luckily, we could pass the extended element to registerElement
because it's implementation looks at the passed object's prototype property!
It's even more important to note that expect IE
(that too to a very small extent) none of the browsers have implemented classes
and we will have to use transpilers like 6to5 or Google's Traceur.
Ok, enough of theory and drawbacks let's see some code!
Basic boilerplate:
1 2 3 4 5 6 7 8 9 10 11 |
|
Now, let's try extending the HTMLSpanElement
(interface).
1 2 3 4 5 6 |
|
Transplied code with 6to5 would look like:
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 |
|
See <date-today></date-today>
working:
Well, it was a silly little custom span element, let's make a better one.
One of favs, <xkcd-img> </xkcd-img>
:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
|
See it in action:
Well, this is just the start, let's hope to see this grow better and faster...untill then happy hacking! :)