Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Dep {
- constructor() {
- this.deps = [];
- }
- static target = null;
- depend() {
- if (Dep.target && this.deps.indexOf(Dep.target) === -1) {
- this.deps.push(Dep.target)
- }
- }
- notify() {
- this.deps.forEach((dep) => { dep() })
- }
- }
- class Observable {
- constructor(obj) {
- return this.walk(obj)
- }
- defineReactive(obj, key, val) {
- const dep = new Dep();
- Object.defineProperty(obj, key, {
- get() {
- dep.depend();
- return val;
- },
- set(newVal) {
- val = newVal;
- dep.notify()
- }
- })
- }
- walk(obj) {
- Object.keys(obj).forEach(key => { this.defineReactive(obj, key, obj[key]) })
- return obj;
- }
- }
- class Watcher {
- constructor(obj, key, cb, onUpdate) {
- this.obj = obj;
- this.key = key;
- this.cb = cb;
- this.onUpdate = onUpdate;
- return this.defineComputedReative();
- }
- defineComputedReative() {
- const self = this;
- const onDepUpdate = () => {
- console.log('1111')
- self.onUpdate(self.cb());
- }
- Object.defineProperty(self.obj, self.key, {
- get() {
- Dep.target = onDepUpdate;
- const value = self.cb();
- Dep.target = null;
- return value;
- }
- })
- }
- }
- function defineReactive(obj, key, val) {
- const deps = [];
- Object.defineProperty(obj, key, {
- get() {
- if (Dep.target && deps.indexOf(Dep.target) === -1) {
- deps.push(Dep.target)
- }
- console.log(`访问了${key}属性`)
- return val
- },
- set(newVal) {
- console.log(`${key}被修改了`)
- val = newVal
- deps.forEach(dep => { dep() })
- }
- })
- }
- // function observable(obj) {
- // Object.keys(obj).forEach((key) => {
- // defineReactive(obj, key, obj[key]);
- // })
- // return obj;
- // }
- // var person = {
- // firstName: 'H',
- // lastName: 'Y'
- // }
- // var p = observable(person)
- // function watcher(obj, key, cb) {
- // const onDepUpdate = () => {
- // const val = cb();
- // console.log('依赖更新了')
- // }
- // Object.defineProperty(obj, key, {
- // get() {
- // Dep.target = onDepUpdate;
- // const value = cb();
- // Dep.target = null
- // return value;
- // },
- // set() {
- // }
- // })
- // }
- // watcher(p, 'fullName', () => {
- // return p.lastName + p.firstName
- // })
- // console.log(p.fullName)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement