Last active
February 18, 2016 19:16
-
-
Save WebReflection/3ee9e8aa33b36e688cfe to your computer and use it in GitHub Desktop.
A simplified way to register Custom Elements
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var DOMClass = (function (O,o) { | |
/*! (C) Andrea Giammarchi */ | |
var | |
create = O.create, | |
css = create(null), | |
dP = O.defineProperty, | |
gOPD = O.getOwnPropertyDescriptor, | |
gOPN = O.getOwnPropertyNames, | |
gOPS = O.getOwnPropertySymbols, | |
ownKeys = gOPS ? | |
function (object) { | |
return gOPN(object).concat(gOPS(object)); | |
} : | |
gOPN, | |
loadCSS = function (document, href) { | |
var | |
head = document.head, | |
link = document.createElement('link') | |
; | |
link.rel = 'stylesheet'; | |
link.type = 'text/css'; | |
link.href = href; | |
css[href] = head.insertBefore(link, head.lastChild); | |
} | |
; | |
return function DOMClass(description) { | |
for (var | |
k, name, xtends, | |
constructor, | |
stylesheet, | |
descriptors = {}, | |
keys = ownKeys(description), | |
set = function (s) { | |
dP(descriptors, s, { | |
enumerable: true, | |
writable: true, | |
value: gOPD(description, k) | |
}); | |
}, | |
i = 0; i < keys.length; i++ | |
) { | |
k = keys[i]; | |
switch (k.toLowerCase()) { | |
case 'name': name = description[k]; break; | |
case 'stylesheet': stylesheet = description[k]; break; | |
case 'extends': | |
xtends = typeof description[k] === 'function' ? | |
description[k].prototype : description[k]; | |
break; | |
case 'constructor': constructor = description[k]; | |
set('createdCallback'); break; | |
case 'onattached': set('attachedCallback'); break; | |
case 'onchanged': set('attributeChangedCallback'); break; | |
case 'ondetached': set('detachedCallback'); break; | |
default: set(k); break; | |
} | |
} | |
if (stylesheet) { | |
descriptors.createdCallback.value = function () { | |
if (!(stylesheet in css)) | |
loadCSS(this.ownerDocument || document, stylesheet); | |
if (constructor) constructor.apply(this, arguments); | |
}; | |
} | |
return document.registerElement( | |
name || ('zero-dom-class-'+ ++o), | |
{prototype: create(xtends || HTMLElement.prototype, descriptors)} | |
); | |
}; | |
}(Object, 0)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Basic usage example.
Full DOMClass Features
The original utility which is capable of doing way more than above snippet is here.