Vue响应式原理浅析

响应式原理

考虑下面的情形:

const state = {
    a: 1
    b: 10
}

如何让a变化的时候,b始终是a的10倍?也就是说像下面这样:

state.a = 2 // 打印"state.b is 20"
state.a = 3 // 打印"state.b is 30"

这其实就是vue的响应式原理,vue依赖Object.defineProperty的get和set函数完成这一功能。

1.1 Getters and Setters

Goal

Implement a convert function that:

expected usage:

const obj = { foo: 123 }
convert(obj)

obj.foo // should log: 'getting key "foo": 123'
obj.foo = 234 // should log: 'setting key "foo" to: 234'
obj.foo // should log: 'getting key "foo": 234'

solution

<script>
function convert (obj) {
  // Implement this!
  Object.keys(obj).forEach(key => {
    let internalValue = obj[key]
    Object.defineProperty(obj, key, {
      get () {
        console.log(`getting key "${key}": ${internalValue}`)
        return internalValue
      },
      set (newValue) {
        internalValue = newValue
        console.log(`setting key "${key}" to: ${newValue}`)
      }
    })
  })
}
</script>

1.2 Dependency Tracking(依赖追踪)

1.watch和computed都是以Vue的依赖追踪机制为基础的,它们都试图处理这样一件事情:当某一个数据(称它为依赖数据)发生变化的时候,所有依赖这个数据的“相关”数据“自动”发生变化,也就是自动调用相关的函数去实现数据的变动。

2.对methods:methods里面是用来定义函数的,很显然,它需要手动调用才能执行。而不像watch和computed那样,“自动执行”预先定义的函数

Goal

完成如下代码,使输出符合预期:

  • Create a Dep class with two methods: depend and notify.(创建一个类Dep,有2个方法:depend和notify)
    • Dep类代表依赖
    • depend 的作用是注册依赖
    • notify 的作用是执行依赖的订阅者:当前依赖改变了,之前的所有依赖Dep这个类的变量(比如函数、表达式等等)需要重新执行,也就是说通知他们Dep发生了改变(依赖的订阅者)
  • Create an autorun function that takes an updater function.(创建一个autorun函数,这个autorun函数接收一个更新函数作为参数)
  • Inside the updater function, you can explicitly depend on an instance of Dep by calling dep.depend()(在更新函数内部可以显示调用dep.depend()
  • Later, you can trigger the updater function to run again by calling dep.notify().(之后可以显示调用dep.notify()触发更新函数)
class Dep {
  // Implement this!
}

function autorun (update) {
  // Implement this!
}
const dep = new Dep()
const update1 = () => {
    dep.depend()
    console.log('111')
}
const update2 = () => {
    dep.depend()
    console.log('222')
}
autorun(update1)
autorun(update2)
dep.notify()
// 期望输出:
// 111
// 222
// 111
// 222

首先声明了一个全局变量activeUpdate,JS是一个单线程语言,无论何时只有一个函数在运行。如果我们创建了一个函数它可以mark自身是否在运行,那么我们在任何时候都可以很轻松地知道这个函数是否在运行,也就是说知道是否在这个函数内部。

然后我们在autorun内部创建一个函数wrappedUpate,在wrappedUpate里执行update函数。我们想要知道的是否在这个update函数内部,所以我们这么做:

class Dep {
  // Implement this!
}

let activeUpdate

function autorun (update) {
  // Implement this!
    function wrappedUpate () {
        activeUpdate = wrappedUpate
        unpdate()
        activeUpdate = null
    }
    wrappedUpate()
}

const dep = new Dep()
const update1 = () => {
    dep.depend()
    console.log('111')
}
const update2 = () => {
    dep.depend()
    console.log('222')
}
autorun(update1)
autorun(update2)
dep.notify()
// 期望输出:
// 111
// 222
// 111
// 222

只要我们运行了wrappedUpate函数,update函数就会运行,在update函数内部我们会调用dep.depend(),这个dep.depend()将会访问全局变量activeUpdate,所以我们在dep.depend()访问activeUpdate之前将其赋值为wrappedUpdate。

这样一来,如果activeUpdate不是空的话,就把activeUpdate指向的变量作为dep的依赖订阅者,完成注册依赖;而notify方法的作用就是把所有的订阅者执行一遍。相应的,Dep需要一个属性存储它的所有订阅者,我们采用Set来存储。

class Dep {
  // Implement this!
    constructor () {
        this.subscribers = new Set()
    }
    depend () {
        if (activeUpdate) {
            // 将当前active update注册为依赖订阅者
            this.subscribers.add(activeUpdate)
        }
    }
    notify () {
        // 执行所有的订阅者
        this.subscribers.forEach(sub => sub())
    }
}

let activeUpdate

function autorun (update) {
  // Implement this!
    function wrappedUpate () {
        activeUpdate = wrappedUpate
        update()
        activeUpdate = null
    }
    wrappedUpate()
}

const dep = new Dep()
const update1 = () => {
    dep.depend()
    console.log('111')
}
const update2 = () => {
    dep.depend()
    console.log('222')
}
autorun(update1)
autorun(update2)
dep.notify

1.3 Mini Observer

现在我们把1.1和1.2结合起来,解决最初提出的问题

Goal

Combine the previous two functions, renaming convert() to observe() and keeping autorun():

  • observe() converts the properties in the received object and make them
    reactive. For each converted property, it gets assigned a Dep instance which keeps track of a list of subscribing update functions, and triggers them to re-run when its setter is invoked.
  • autorun() takes an update function and re-runs it when properties that the
    update function subscribes to have been mutated. An update function is said
    to be "subscribing" to a property if it relies on that property during its
    evaluation.

They should support the following usage:

const state = {
    a: 1
}

observe(state)
computed(() => {
    state.b = state.a * 10
    console.log(`state.b is: ${state.b}`)
})

state.a = 2
state.a = 3

Solutions

class Dep {
  constructor () {
    this.subscribers = new Set()
  }
  depend () {
    if (activeUpate) {
      this.subscribers.add(activeUpate)
    }
  }
  notify () {
    this.subscribers.forEach(sub => sub())
  }
}

let activeUpate

function observe (obj) {
  // Implement this!
  let dep = new Dep()
  Object.keys(obj).forEach(key => {
    let internalValue = obj[key]
    Object.defineProperty(obj, key, {
      get () {
        dep.depend()
        return internalValue
      },
      set (newValue) {
        let changed = internalValue !== newValue
        internalValue = newValue
        if (changed) {
          dep.notify()
        }
      }
    })
  })
}

function computed (update) {
  // Implement this!
  function wrapperUpdate () {
    activeUpate = wrapperUpdate
    update()
    activeUpate = null
  }
  wrapperUpdate()
}

我们只是把1.1中的convert函数改名为observer,autorun改名computed,然后在get和set函数中调用dep.depend()和dep.notify(),剩下的都是前面讲过的代码了,不必多说。

(finished)

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,591评论 6 501
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,448评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,823评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,204评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,228评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,190评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,078评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,923评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,334评论 1 310
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,550评论 2 333
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,727评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,428评论 5 343
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,022评论 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,672评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,826评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,734评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,619评论 2 354

推荐阅读更多精彩内容