Skip to content

Instantly share code, notes, and snippets.

@deebloo
Last active January 4, 2021 12:34
Show Gist options
  • Save deebloo/79fb41f5d596266b8ca1 to your computer and use it in GitHub Desktop.
Save deebloo/79fb41f5d596266b8ca1 to your computer and use it in GitHub Desktop.
A pattern for creating vanilla web components. no library. just a pattern I am rolling around.
(function () {
expose('createMyComponent', register, factory);
/**
* Exposes your new component to the window or to a module
*
* @param {string} name - the factory name to expose
* @param {function} definition - the definition of your web component. registers to the document
* @param {function} factory - method for programmatically creating web component
*/
function expose(name, definition, factory) {
var Component = definition();
if (typeof exports === 'object') {
if (typeof module === 'object' && typeof module.exports === 'object') {
module.exports = exposeFactory;
}
exports[name] = exposeFactory;
return exposeFactory;
}
this[name] = exposeFactory;
function exposeFactory(opts) {
return factory(Component, opts);
}
return exposeFactory;
}
/**
* !!!This will be the only part you should have to change other then names
*
* Create and register your web component with the document
*/
function register() {
var doProto = Object.create(HTMLElement.prototype);
return document.registerElement('my-component', {
prototype: doProto
});
}
/**
* factory for creating new dynamic instance of the component
*
* @param {function} Component - the registered component Constructor/class
* @param {object} options - a map of attributes to attach to the new component instance
*
* @return {*}
*/
function factory(Component, options) {
var newEl = new Component();
for(var option in options) {
if(options.hasOwnProperty(option)) {
newEl.setAttribute(option, options[option]);
}
}
return newEl;
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment