This is a thorough understanding of the Vue watch realization of the principle and its implementation (rpm)

Draw a simple flow chart of the watch:

The Dep above, Oberver, Wather take over and make some of the changes (increase reliance collect the deduplication processing):

Dep code is as follows:

// identify the current Dep id
let uidep = 0
class Dep{
    constructor () {
        this.id uidep ++ =
        // store all listening watcher
        this.subs = []
      }
 
      // add an observer objects
      addSub (Watcher) {
        this.subs.push(Watcher)
      }
 
      // rely on collection
    depend () {
        //Dep.target role will only need to collect dependent
        if (Dep.target) {
          Dep.target.addDep(this)
        }
    }
 
    // Call depend collected Watcher update
    notify () {
        const subs = this.subs.slice()
        for (let i = 0, l = subs.length; i < l; i++) {
          subs[i].update()
        }
      }
}
 
Dep.target = null
const targetStack = []
 
// assign to Dep.target

function pushTarget (Watcher) {
if (Dep.target) targetStack.push(Dep.target)
Dep.target = Watcher
}
function popTarget () {
Dep.target = targetStack.pop()
}

 

Guess you like

Origin www.cnblogs.com/niechencn/p/11095996.html