Skip to content

Instantly share code, notes, and snippets.

@suukii
Last active September 17, 2020 08:41
Show Gist options
  • Save suukii/ed55d5d1b155ea01ca3a35fd52cd30ce to your computer and use it in GitHub Desktop.
Save suukii/ed55d5d1b155ea01ca3a35fd52cd30ce to your computer and use it in GitHub Desktop.
从零实现一个响应式状态管理
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>State Reactivity</title>
</head>
<body>
<script>
function observe(obj) {
Object.keys(obj).forEach(key => {
let internalValue = obj[key];
const dep = new Dep();
Object.defineProperty(obj, key, {
get() {
dep.depend();
return internalValue;
},
set(newVal) {
internalValue = newVal;
dep.notify();
},
});
});
}
class Dep {
constructor() {
this.subscribers = new Set();
}
depend() {
activeUpdate && this.subscribers.add(activeUpdate);
}
notify() {
this.subscribers.forEach(func => func());
}
}
function log() {
console.log(`update state.count to ${state.count}`);
}
let activeUpdate = null;
function autorun(update) {
function wrappedUpdate() {
activeUpdate = update;
update();
activeUpdate = null;
}
wrappedUpdate();
}
const state = {
count: 1,
};
observe(state);
autorun(log);
setTimeout(() => {
state.count += 1;
}, 2000);
setTimeout(() => {
state.count += 1;
}, 3000);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment