美文网首页
mobx模拟

mobx模拟

作者: 立陶宛_d5a9 | 来源:发表于2019-11-15 20:21 被阅读0次

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 = '不依赖'

相关文章

网友评论

      本文标题:mobx模拟

      本文链接:https://www.haomeiwen.com/subject/iqdcictx.html