Skip to content

Instantly share code, notes, and snippets.

@keidarcy
Last active April 20, 2020 09:21
Show Gist options
  • Save keidarcy/bd89e427ce2ca0a538ff896c353c2444 to your computer and use it in GitHub Desktop.
Save keidarcy/bd89e427ce2ca0a538ff896c353c2444 to your computer and use it in GitHub Desktop.
implement js reactivity
let data = { price: 5, quantity: 2 };
let target = null;
let total = 0;
class Dep {
constructor() {
this.subscribers = [];
}
depend() {
if (target && !this.subscribers.includes(target)) {
this.subscribers.push(target);
}
}
notify() {
this.subscribers.forEach((sub) => sub());
}
}
let deps = new Map();
Object.keys(data).forEach((key) => {
deps.set(key, new Dep());
});
let data_without_proxy = data;
data = new Proxy(data_without_proxy, {
get(obj, key) {
deps.get(key).depend();
return obj[key];
},
set(obj, key, newValue) {
obj[key] = newValue;
deps.get(key).notify();
return true;
}
});
//Object.keys(data).forEach((key) => {
// let internalValue = data[key];
// const dep = new Dep();
// Object.defineProperty(data, key, {
// get() {
// dep.depend();
// console.log(`Getting ${key}: ${internalValue}`);
// return internalValue;
// },
// set(newVal) {
// console.log(`Setting ${key} to: ${newVal}`);
// internalValue = newVal;
// dep.notify();
// }
// });
//});
const watcher = (myFunc) => {
target = myFunc;
target();
target = null;
};
watcher(() => {
total = data.price * data.quantity;
});
console.log(total);
data.price = 100;
console.log(total);
let data = { price: 5, quantity: 2}
let target = null
class Dep {
constructor() {
this.subscribers = []
}
depend() {
if (target && !this.subscribers.includes(target)) {
this.subscribers.push(target)
}
}
notify() {
this.subscribers.forEach(sub => sub())
}
}
Object.keys(data).forEach(key => {
let internalValue = data[key]
const dep = new Dep()
Object.defineProperty(data,key, {
get() {
dep.depend()
console.log(`Getting ${key}: ${internalValue}`)
return internalValue
},
set(newVal) {
console.log(`Setting ${key} to: ${newVal}`)
internalValue = newVal
dep.notify()
}
})
})
const watcher = (myFunc) => {
target = myFunc
target()
target = null
}
watcher(() => {
data.total = data.price * data.quantity
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment