Last active
December 12, 2015 01:33
-
-
Save ZauberNerd/43972f4ffba14d25b172 to your computer and use it in GitHub Desktop.
Property trap (inspired by ES6 proxies)
This file contains 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 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; | |
} |
This file contains 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
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