|
| 1 | +// 原文地址:https://segmentfault.com/a/1190000006599500 |
| 2 | +var data = { name: "gzz" }; |
| 3 | +observe(data); |
| 4 | +data.name = "zl"; // 就会有输出 |
| 5 | + |
| 6 | +function observe(data) { |
| 7 | + if (!data || typeof data !== "object") return; |
| 8 | + Object.keys(data).forEach((key) => { |
| 9 | + defineReactive(data, key, data[key]); |
| 10 | + }); |
| 11 | +} |
| 12 | + |
| 13 | +function defineReactive(data, key, val) { |
| 14 | + var dep = new Dep(); |
| 15 | + observe(val); // 子属性也是对象 |
| 16 | + Object.defineProperty(data, key, { |
| 17 | + enumerable: true, |
| 18 | + configurable: false, |
| 19 | + get: function () { |
| 20 | + Dep.target && dep.addSub(Dep.target); |
| 21 | + return val; |
| 22 | + }, |
| 23 | + set: function (newVal) { |
| 24 | + if (val === newVal) return; |
| 25 | + console.log("哈哈哈,监听到值变化了 ", val, " --> ", newVal); |
| 26 | + val = newVal; |
| 27 | + dep.notify(); |
| 28 | + }, |
| 29 | + }); |
| 30 | +} |
| 31 | +class Dep { |
| 32 | + constructor() { |
| 33 | + this.subs = []; |
| 34 | + } |
| 35 | + addSub(sub) { |
| 36 | + this.subs.push(sub); |
| 37 | + } |
| 38 | + notify() { |
| 39 | + this.subs.forEach((sub) => sub.update()); |
| 40 | + } |
| 41 | +} |
| 42 | + |
| 43 | +class Watcher { |
| 44 | + get(key) { |
| 45 | + Dep.target = this; |
| 46 | + this.value = data[key]; // 访问一下data的属性,就会触发 getter 劫持,从而添加订阅者 |
| 47 | + Dep.target = null; |
| 48 | + } |
| 49 | +} |
| 50 | + |
| 51 | +// 为了提升性能,会先将根节点 el 转换成文档碎片 fragment 进行解析编译操作,解析完成,再将 fragment 添加回原来的真实 dom 节点中 |
| 52 | +function Compile(el) { |
| 53 | + this.$el = this.isElementNode(el) ? el : document.querySelector(el); |
| 54 | + if (this.$el) { |
| 55 | + this.$fragment = this.node2Fragment(this.$el); |
| 56 | + this.init(); |
| 57 | + this.$el.appendChild(this.$fragment); |
| 58 | + } |
| 59 | +} |
| 60 | +Compile.prototype = { |
| 61 | + init: function () { |
| 62 | + this.compileElement(this.$fragment); |
| 63 | + }, |
| 64 | + node2Fragment: function (el) { |
| 65 | + var fragment = document.createDocumentFragment(), |
| 66 | + child; |
| 67 | + // 将原生节点拷贝到fragment |
| 68 | + while ((child = el.firstChild)) { |
| 69 | + fragment.appendChild(child); |
| 70 | + } |
| 71 | + return fragment; |
| 72 | + }, |
| 73 | +}; |
0 commit comments