Skip to content

Instantly share code, notes, and snippets.

@dux
Last active May 20, 2019 21:13
Show Gist options
  • Save dux/516bcc6f4faf12fb29502a9961716ca2 to your computer and use it in GitHub Desktop.
Save dux/516bcc6f4faf12fb29502a9961716ca2 to your computer and use it in GitHub Desktop.
DOM create customElement or polyfil for older browsers. passes node + attributes
// for svelte js, or any othe widget provider
let bindSvelteToDOM = function(name, klass) {
DOMCustomElement.define(name, function(node, opts) {
node.classList.add('mounted')
new klass({ target: node, props: opts })
})
}
import SvelteCheckbox from './svelte/checkbox.svelte'
bindSvelteToDOM('s-checkbox', SvelteCheckbox)
/*
will render custom checkbox, from server rendered pages
<div>
<s-checkbox name="foo" label="bar"></s-checkbox>
</div>
*/
# DOM custom element or polyfil for older browsers
window.DOMCustomElement =
ping_interval: 100
data: {}
attributes: (node) ->
o = {}
i = 0
while el = node.attributes[i]
o[el.name] = el.value;
i++
o
define: (name, func) ->
if window.customElements
customElements.define name, class extends HTMLElement
constructor: ->
super()
window.requestAnimationFrame =>
func @, DOMCustomElement.attributes(@)
else
@data[name] = func
bind: ->
for name, func of @data
for node in Array.from(document.querySelectorAll("#{name}:not(.mounted)"))
func node, @attributes(node)
init: ->
setInterval =>
@bind()
, @ping_interval
DOMCustomElement.init()
// create DOM custom element or polyfil for older browsers
window.DOMCustomElement = {
ping_interval: 200,
data: {},
attributes: function(node) {
var el, i, o;
o = {};
i = 0;
while (el = node.attributes[i]) {
o[el.name] = el.value;
i++;
}
return o;
},
define: function(name, func) {
if (window.customElements) {
return customElements.define(name, class extends HTMLElement {
constructor() {
super();
window.requestAnimationFrame(() => {
return func(this, DOMCustomElement.attributes(this));
});
}
});
} else {
return this.data[name] = func;
}
},
bind: function() {
var func, name, node, ref, results;
ref = this.data;
results = [];
for (name in ref) {
func = ref[name];
results.push((function() {
var j, len, ref1, results1;
ref1 = Array.from(document.querySelectorAll(`${name}:not(.mounted)`));
results1 = [];
for (j = 0, len = ref1.length; j < len; j++) {
node = ref1[j];
results1.push(func(node, this.attributes(node)));
}
return results1;
}).call(this));
}
return results;
},
init: function() {
return setInterval(() => {
return this.bind();
}, this.ping_interval);
}
};
DOMCustomElement.init();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment