Giter Club home page Giter Club logo

reactive-data's Introduction

响应式系统是vue的一个独特特性。它通过无法shim的ES5对象描述符中的getter和setter来实现观察者模式。在getter中添加观察者,并且在setter中通知观察者执行变化。

标准的观察者模式如下: ![观察者模式]('./doc/observe pattern.png')

在vue实例的初始化过程中,将会为data的每一个属性视为观察目标,并且为每一个属性维护一个deps数组,用来收集这个属性的watcher

export function defineReactive(ob, key, val){
  // 执行观察
  let childObserve = observe(val),
    dep = new Dep()
  Object.defineProperty(ob, key, {
    configurable: true,
    enumerable: true,
    get: () => {
      if(Dep.target){
        // 依赖收集
        // Dep.target 是一个watcher
        dep.addDep(Dep.target)
      }
      return val 
    },
    set: newVal => {
      if(newVal === val) return 
      val = newVal 
      // 如果新赋值的是个object
      childObserve = observe(val)
      dep.notify()
    }
  })
}

当设置data属性的时候,就会触发dep的notify方法,依次调用watcher的回调函数

npm run test // 执行测试

reactive-data's People

Watchers

James Cloos avatar maurice avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.