var globalID = 0;
function observable(obj) {
var oID = ++globalID;
return new Proxy(obj, {
get: function(target, key, receiver) {
collect.startCollect(oID + "" + key);
return Reflect.get(target, key, receiver);
},
set: function(target, key, value, receiver) {
Reflect.set(target, key, value, receiver);
collection[oID + "" + key] &&
collection[oID + "" + key].forEach(c => {
c();
});
}
});
}
var collection = {};
var collect = {
begin: function(handler) {
collection.handler = handler;
collection.now = true;
},
startCollect: function(oIDKey) {
if (collection.now) {
if (collection[oIDKey]) {
collection[oIDKey].push(collection.handler);
} else {
collection[oIDKey] = [collection.handler];
}
}
},
end: function() {
collection.now = false;
}
};
function autorun(handler) {
collect.begin(handler);
handler();
collect.end();
}
var obj = observable({
a: 1,
b: 2
});
autorun(() => {
console.log("obj.a test1", obj.a);
});
// autorun(() => {
// console.log("obj.a test2", obj.a);
// });
obj.a = '依赖'
obj.b = '不依赖'
网友评论