Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

031.Reactive #31

Open
mewcoder opened this issue Mar 21, 2024 · 1 comment
Open

031.Reactive #31

mewcoder opened this issue Mar 21, 2024 · 1 comment

Comments

@mewcoder
Copy link
Owner

mewcoder commented Mar 21, 2024

实现一个 Reactive 方法,返回可监听 key 变化的函数

// 实现
function Reactive() {
  // ...
}

// 测试
const obj = { a: 1, b: 2 };

const reactive = Reactive(obj);
reactive.subscribe((key, oldValue, newValue) => {
  console.log(key, oldValue, newValue);
});

reactive.state.a = 3; // console.log('a', 1,2)
reactive.state.c = 10; //console.log('c', undefined, 10)
@mewcoder
Copy link
Owner Author

function Reactive(obj) {
  handlers = [];

  const subscribe = (handler) => {
    handlers.push(handler);
  };

  const notify = (key, oldValue, newValue) => {
    handlers.forEach((handler) => handler(key, oldValue, newValue));
  };

  const proxy = new Proxy(obj, {
    set(target, key, value) {
      if (value !== target[key]) {
        notify(key, target[key], value);
        target[key] = value;
      }
      return true;
    },
  });

  return {
    subscribe,
    state: proxy,
  };
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant