function defineReactive(obj, key, val) {
observe(val)
const dep = new Dep()
Object.defineProperty(obj, key, {
get() {
console.log('get', key);
Dep.target && dep.addDep(Dep.target)
return val
},
set(newVal) {
if (newVal !== val) {
console.log('set', key, newVal);
observe(newVal)
val = newVal
dep.notify()
}
},
})
}
function observe(obj) {
if (typeof obj !== 'object' || obj == null) {
return
}
new Observer(obj)
}
function proxy(vm) {
Object.keys(vm.$data).forEach(key => {
Object.defineProperty(vm, key, {
get() {
return vm.$data[key]
},
set(v) {
vm.$data[key] = v
}
})
})
}
class KVue {
constructor(options) {
this.$options = options
this.$data = options.data;
observe(this.$data)
proxy(this)
new Compiler('#app', this)
}
}
class Observer {
constructor(value) {
this.value = value
this.walk(value)
}
walk(obj) {
Object.keys(obj).forEach(key => {
defineReactive(obj, key, obj[key])
})
}
}
class Compiler {
constructor(el, vm) {
this.$vm = vm
this.$el = document.querySelector(el)
this.compile(this.$el)
}
compile(el) {
el.childNodes.forEach(node => {
if (node.nodeType === 1) {
this.compileElement(node)
} else if (this.isInter(node)) {
this.compileText(node)
}
if (node.childNodes) {
this.compile(node)
}
})
}
compileText(node) {
this.update(node, RegExp.$1, 'text')
}
compileElement(node) {
const attrs = node.attributes
Array.from(attrs).forEach(attr => {
const attrName = attr.name
const exp = attr.value
if (attrName.indexOf('k-') === 0) {
const dir = attrName.substring(2)
this[dir] && this[dir](node, exp)
}
})
}
text(node, exp) {
this.update(node, exp, 'text')
}
html(node, exp) {
this.update(node, exp, 'html')
}
update(node, exp, dir) {
const fn = this[dir + 'Updater']
fn && fn(node, this.$vm[exp])
new Watcher(this.$vm, exp, val => {
fn && fn(node, val)
})
}
textUpdater(node, val) {
node.textContent = val
}
htmlUpdater(node, val) {
node.innerHTML = val
}
isInter(node) {
return node.nodeType === 3 && /\{\{(.*)\}\}/.test(node.textContent)
}
}
class Watcher {
constructor(vm, key, updateFn) {
this.vm = vm
this.key = key
this.updateFn = updateFn
Dep.target = this
vm[key]
Dep.target = null
}
update() {
this.updateFn.call(this.vm, this.vm[this.key])
}
}
class Dep {
constructor() {
this.deps = []
}
addDep(watcher) {
this.deps.push(watcher)
}
notify() {
this.deps.forEach(dep => dep.update())
}
}
转载请注明原文地址:https://ipadbbs.8miu.com/read-8668.html