moy-dom
Version:
A flexiable Virtual DOM library for building modern web interface.
72 lines (63 loc) • 1.71 kB
JavaScript
import {
domAttrs,
boolAttrs,
} from './specialAttrs'
export default class Element {
constructor(tagName, props, children){
this.tagName = tagName
this.props = props
this.key = props.key
let count = 0,
childrenFilter = [],
length = children.length,
child
for(let i = 0; i < length; i ++){
child = children[i]
if(child !== null){
if(Object.prototype.toString.call(child) === '[object Element]'){
count += child.count + 1
childrenFilter.push(child)
}else{
count ++
childrenFilter.push('' + child)
}
}
}
this.children = childrenFilter
this.count = count
}
render(){
const el = document.createElement(this.tagName)
for(let [propKey, propValue] of Object.entries(this.props)){
if(domAttrs[propKey] || /^on\w+/.test(propKey)){
el[propKey] = propValue === undefined ? null : propValue
}else if(boolAttrs[propKey]){
if(propValue){
el.setAttribute(propKey, propKey)
}
}else{
if(propValue !== undefined){
el.setAttribute(propKey, propValue)
}
}
}
for(let child of this.children){
el.appendChild(
Object.prototype.toString.call(child) === '[object Element]' ?
child.render() :
document.createTextNode(child)
)
}
return el
}
static of(tagName, props = {}, ...children){
if(Object.prototype.toString.call(props) !== '[object Object]'){
children.unshift(props)
props = {}
}
return new Element(tagName, props, children)
}
get [Symbol.toStringTag]() {
return 'Element'
}
}