• Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.
  1. Dep

Depend collects dependencies and notify triggers dependencies

class Dep{ constructor() { this._subs = []; } depend () { this._subs.push(Dep.target) } notify() { this._subs.forEach(item => { item.fn(); // Dep = null; // Dep = null; // Dep = null; function pushTarget(watch) { Dep.target = watch; } function popTarget() { Dep.target = null; }Copy the code
  1. Understand obverser

Recursively, converting all properties of a data object to accessor properties

Function defineReactive (obj, key, val, shallow) {let dep = new dep (); let childOb = ! shallow && observe(val) Object.defineProperty(obj, key, { enumerable: true, configurable: true, get: Function reactitter () {if(dep.target) {// Collect depend on dep.depend(); } return val; / /... }, set: function reactiveSetter (newVal) { if(newVal === val) return; // continue recursively through observe(newVal); // Trigger dependency dep.notify(); / /... } }) } class Observer{ constructor(data) { this.walk(data); } walk(data) { const keys = Object.keys(data) for (let i = 0; i < keys.length; I ++) {defineReactive(data, keys[I], data[keys[I]])}}} All the data Object into the accessor attribute function observe (data) {if (Object. The prototype. ToString. Call (data)! == '[object Object]') return; new Observer(data); }Copy the code

All attributes of any object can then be converted to accessors

  1. Learn about watch and Observer
Const data = {a: 1, b: 2} // Observe (data);Copy the code

Watcher’s main function is to detect a property and trigger a callback when the property changes

Constructor (exp, fn) {this.exp = exp; /** * @constructor (exp, fn) {this.exp = exp; /** * @constructor (exp, fn) {this.exp = exp;  this.fn = fn; // dep. target = this; pushTarget(this); A get is executed, and dep.depend() starts collecting dependencies this.exp(); // Release dep.target popTarget(); New Watcher(() => {return data.a + data.b; }, () => { console.log('change') })Copy the code
  1. Trigger rely on
data.a = 3; // change
data.b = 3; // change
Copy the code

process

Summarize the process

  1. Convert all attributes of an object to accessors
  2. When you add a watcher to an attribute, the get of the modified attribute is triggered, and the GET function stores the watcher in the DEP dependency container of the attribute
  3. When the attribute is changed, the set method is used to change the attribute. The set function executes all the deP stored dependencies