Skip to content

Instantly share code, notes, and snippets.

@ZauberNerd
Last active December 12, 2015 01:33
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ZauberNerd/43972f4ffba14d25b172 to your computer and use it in GitHub Desktop.
Save ZauberNerd/43972f4ffba14d25b172 to your computer and use it in GitHub Desktop.
Property trap (inspired by ES6 proxies)
function isObject(test) {
return Object.prototype.toString.call(test) === '[object Object]';
}
function trap(host, targetName, handler) {
const prison = {};
let cell = {};
Object.defineProperty(prison, targetName, {
configurable: true,
enumerable: host.propertyIsEnumerable(targetName),
get() {
if (!isObject(cell)) {
return cell;
}
const trap = Object.assign({}, cell);
setTimeout(() => {
for (let key in trap) {
if (trap.hasOwnProperty(key)) {
if (cell[key] !== trap[key]) {
cell[key] = handler(host, key, trap[key]);
}
}
}
}, 0);
return trap;
},
set(value) {
return cell = handler(host, null, value);
}
});
return prison;
}
const body = trap(document.body, 'style', (host, property, value) => {
console.log('something changed', property, value);
// do your magic here
// host.style[property] = value;
return value;
});
body.style.opacity = '0';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment