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
| function Compile(el, vm) { this.vm = vm this.el = document.querySelector(el) this.init() }
Compile.prototype = { init: function () { if (this.el) { this.fragment = this.nodeToFragment(this.el) this.compileElement(this.fragment) this.el.appendChild(this.fragment) return } console.log('DOM不存在') }, nodeToFragment: function(el) { var fragment = document.createDocumentFragment() var child = el.firstChild while(child) { fragment.appendChild(child) child = el.firstChild } return fragment }, compileElemnt: function (el) { var childNodes = el.childNodes var self = this
Array.prototype.slice.call(childNodes).forEach(node => { var reg = /\{\{\s*(.*?)\s*\}\}/ var text = node.textContent
if (self.isElementNode(node)) { self.compile(node) } else if (self.isTextNode(node) && reg.test(text)) { self.compileText(node, reg.exec(text)[1]) }
if (node.childNodes && node.childNodes.length) { self.compileElement(node) } }) }, compile: function (node) { var nodeAttrs = node.attributes var self = this
Array.prototype.forEach.call(nodeAttrs, attr => { var attrName = attr.name if (self.isDirective(attrName)) { var exp = attr.value var dir = attrName.substring(2)
if (self.isEventDirective(dir)) { self.compileEvent(node, self.vm, exp, dir) } else { self.compileModel(node, self.vm, exp, dir) }
node.removeAttribute(attrName) } }) }, compileEvent: function (node, vm, exp, dir) { var eventType = dir.split(':')[1] var cb = vm.methods && vm.methods[exp]
if (eventType && cb) node.addEventListener(eventType, cb) }, compileModel: function (node, vm, exp, dir) { var self = this var val = vm[exp] this.modelUpdater(node, val) new Watcher(this.vm, exp, value => self.modelUpdater(node, value)) node.addEventListener('input', e => { var newVal = e.target.value if (val === newVal) return self.vm[exp] = newVal val = newVal }) }, compileText: function (node, exp) { var self = this var text = self.vm[exp] this.updateText(node, text) new Watcher(this.vm, exp, value => self.updateText(node, value)) }, isElementNode: function (node) { return node.nodeType === 1 }, isTextNode: function (node) { return node.nodeType === 3 }, isDirective: function (attr) { return attr.indexOf('v-') === 0 }, isEventDirective: function (attr) { return attr.indexOf('on:') === 0 }, modelUpdater: function (node, value) { node.value = typeof value == 'undefined' ? '' : value }, updateText: function (node, value) { node.textContent = typeof value == 'undefined' ? '' : value } }
|