使用proxy来简单的实现一个观察者

时间:2022-04-13 03:48:20
        var obv = (function() {

            var cache = new Map();

            var observe = function (proxy, fn) {
if (!cache.has(proxy)) {
cache.set(proxy, []);
};
cache.get(proxy).push(fn);
}; var observData = function(obj) {
return new Proxy(obj, {
set: function(target, key, value, receiver) {
var old = target[key];
if (old !== value) {
var result = Reflect.set(target, key, value, receiver);
var arr = cache.get(receiver);
arr && arr.forEach(function(observer) {
return observer.call(target, key, value, old);
});
return result;
};
}
});
}; return {
observe: observe,
observData: observData
};
}());

使用姿势:

1.使用

obv.observData

监听一个数组或者一个对象;

2.然后使用

obv.observe

来监听回调函数,第一个参数就是Proxy的实例,第二个参书就是其对应的回调
        var person = obv.observData({
name: '徐志伟',
age: 26
}); var pp = obv.observData({
personality: '哈哈',
abc: '去屎'
}); var dd = obv.observData([1, 2, 3, 4]); function print(key, value, old) {
console.log(key, value, old);
};
function print2(key, value, old) {
console.log(key, value, old);
}; obv.observe(dd, print);
obv.observe(dd, print2);
// person.name = '徐志伟1';
// pp.personality = '斤斤计较军军军军';
dd[0] = "111";