-
Notifications
You must be signed in to change notification settings - Fork 17
/
custom-element-v1.js
43 lines (40 loc) · 1.28 KB
/
custom-element-v1.js
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
33
34
35
36
37
38
39
40
41
42
43
const assert = require('assert')
module.exports = toCustomElementV1
function toCustomElementV1 (Nanocomponent, attrs = []) {
assert.equal(typeof Nanocomponent, 'function', 'nanocomponent-adapters/custom-elements-v1: Nanocomponent should be type function')
assert.equal(typeof attrs, 'object', 'nanocomponent-adapters/custom-elements-v1: attrs should be type Array')
class NanoEl extends window.HTMLElement {
constructor () {
super()
this.props = {}
this.comp = new Nanocomponent()
}
static get observedAttributes () { return attrs }
connectedCallback () {
const newProps = {}
if (this.hasAttributes()) {
const len = attrs.length
const mattrs = this.attributes
for (let i = 0; i < len; i++) {
if (attrs.includes(mattrs[i].name)) {
newProps[mattrs[i].name] = mattrs[i].value
}
}
}
this.props = newProps
if (!this.comp.element) {
var el = this.comp.render(this.props)
this.appendChild(el)
}
}
disconnectedCallback () {
this.props = null
this.comp = null
}
attributeChangedCallback (attr, oldVal, newVal) {
this.props[attr] = newVal
if (this.comp.element) this.comp.render(this.props)
}
}
return NanoEl
}