Skip to content

Instantly share code, notes, and snippets.

@zeitiger
Created July 13, 2016 07:28
Show Gist options
  • Save zeitiger/d472decaed90e3ed330c2ad154f47f15 to your computer and use it in GitHub Desktop.
Save zeitiger/d472decaed90e3ed330c2ad154f47f15 to your computer and use it in GitHub Desktop.
Register low level custom elements dynamic on the fly for v0 and v1
const noop = () => undefined;
/**
*
* @param {string} elementName
* @param {string} sourceTagName
* @param {object} sourcePrototype
* @param {function} setup
* @param {function} destroy
* @see https://developers.google.com/web/fundamentals/primers/customelements/
*/
export default ({elementName, sourceTagName, sourcePrototype, setup=noop, destroy=noop}) => {
if('customElements' in window) { // custom elements v1
const intermediateConstructor = function() {
console.log(`construct ${elementName}`);
};
intermediateConstructor.prototype = Object.create(
sourcePrototype,
{
connectedCallback: {
value: setup
},
disconnectedCallback: {
value: destroy
}
}
);
/**
* Expect as 2nd parameter an ES6 class like constructor, so we construct that here on the fly
*/
window.customElements.define(elementName, intermediateConstructor);
} else { // custom element v0
// TODO if this issue (https://github.com/WebReflection/document-register-element/issues/58) is resolved we need to rewrite this function call
/**
* Expect as 2nd parameter a configuration object
*/
document.registerElement(elementName, {
extends: sourceTagName,
prototype: Object.create(
sourcePrototype,
{
attachedCallback: {
value: setup
},
detachedCallback: {
value: destroy
}
}
)
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment