Created
September 25, 2017 15:53
-
-
Save janryWang/816ee537fda3adff7cf9b7a0811e3785 to your computer and use it in GitHub Desktop.
借助Proxy实现一个obseve
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function observe(target, handler) { | |
var timer = {} | |
function _trigger(name, ...args) { | |
if (handler && typeof handler[name] === "function") { | |
if (!hanlder.sync) { | |
clearTimeout(timer[name]) | |
timer[name] = setTimeout(function() { | |
handler[name](...args) | |
}, 17) | |
} else { | |
handler[name](...args) | |
} | |
} | |
} | |
function _observe(target, path = []) { | |
if (Array.isArray(target)) { | |
return new Proxy( | |
target.map((item, key) => _observe(item, path.concat(key))), | |
{ | |
get: function(obj, key) { | |
_trigger("get", { | |
target: obj, | |
propKey: key, | |
path: path.concat(key) | |
}) | |
return obj[key] | |
}, | |
set: function(obj, key, value) { | |
var old = obj[key] | |
value = _observe(value, path.concat(key)) | |
obj[key] = value | |
_trigger("set", { | |
target: obj, | |
propKey: key, | |
value: value, | |
oldValue: old, | |
path: path.concat(key) | |
}) | |
return true | |
}, | |
deleteProperty: function(obj, key) { | |
_trigger("delete", { | |
target: obj, | |
propKey: key, | |
path: path.concat(key) | |
}) | |
delete obj[key] | |
return true | |
} | |
} | |
) | |
} else if (typeof target === "object") { | |
if (target instanceof Proxy) return taregt | |
return new Proxy( | |
Object.keys(target).reduce((buf, key) => { | |
buf[key] = _observe(target[key], path.concat(key)) | |
return buf | |
}, {}), | |
{ | |
get: function(obj, key) { | |
_trigger("get", { | |
target: obj, | |
propKey: key, | |
path: path.concat(key) | |
}) | |
return obj[key] | |
}, | |
set: function(obj, key, value) { | |
var old = obj[key] | |
value = _observe(value, path.concat(key)) | |
obj[key] = value | |
_trigger("set", { | |
target: obj, | |
propKey: key, | |
value: value, | |
oldValue: old, | |
path: path.concat(key) | |
}) | |
return true | |
}, | |
deleteProperty: function(obj, key) { | |
_trigger("delete", { | |
target: obj, | |
propKey: key, | |
path: path.concat(key) | |
}) | |
delete obj[key] | |
return true | |
} | |
} | |
) | |
} else { | |
return target | |
} | |
} | |
return _observe(target) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment