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 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167
|
class Compile { constructor(el, vm) { this.vm = vm this.el = document.querySelector(el) this.fragment = null this.init() }
init() { if (this.el) { this.fragment = this.nodeToFragment(this.el) this.compileElement(this.fragment) this.el.appendChild(this.fragment) } else { console.log(`Cannot find this element '${el}'`) } }
nodeToFragment(el) { const oFragment = document.createDocumentFragment() let child = el.firstChild
while (child) { oFragment.appendChild(child) child = el.firstChild }
return oFragment }
compileElement(el) { const childNodes = el.childNodes
childNodes.forEach(node => { const reg = /\{\{\s*(.*?)\s*\}\}/ const text = node.textContent const nodeAttrs = node.attributes
if (this.isTextNode(node)) { if (reg.test(text)) { this.compileText(node, reg.exec(text)[1]) } return }
if (this.isElementNode) { Array.prototype.forEach.call(nodeAttrs, (attr) => { const attrName = attr.name if (this.isDirective(attrName)) { const exp = attr.value const directive = attrName.substring(2) if (this.isEventDirective(attrName)) { this.compileEvent(node, this.vm, exp, directive) } else { this.compileModel(node, this.vm, exp, directive) } } }) }
if (node.childNodes && node.childNodes.length) { this.compileElement(node) } }) }
compileModel(node, vm, exp, dir) { const value = this.vm[exp] this.updateModel(node, value) new Watcher(this.vm, exp, (value) => { this.updateModel(node, value) })
node.addEventListener('input', function(e) { const newValue = e.target.value if (value === newValue) { return } vm[exp] = newValue }) }
compileEvent(node, vm, exp, dir) { const eventType = dir.split(':')[1] const cb = vm.methods && vm.methods[exp]
if (eventType && cb) { node.addEventListener(eventType, cb.bind(vm), false) } }
compileText(node, exp) { const initText = this.vm[exp]
this.updateText(node, initText)
new Watcher(this.vm, exp, (value) => { this.updateText(node, value) }) }
updateText(node, value) { node.textContent = typeof value === 'undefined' ? '' : value }
updateModel(node, newValue, oldValue) { node.value = typeof newValue === 'undefined' ? '' : newValue }
isDirective(attr) { return attr.indexOf('v-') === 0 }
isEventDirective(attr) { return attr.indexOf('on:') === 2 }
isTextNode(node) { return node.nodeType === 3 }
isElementNode(node) { return node.nodeType === 1 } }
|