Created
August 8, 2017 19:35
-
-
Save pofigizm/311d2390152bbe31f25867a8fca61ab2 to your computer and use it in GitHub Desktop.
Waiting for define deep property in window object
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 waitForProp = (prop, context) => new Promise(resolve => { | |
if (typeof context[prop] !== 'undefined') { | |
resolve(context[prop]) | |
return | |
} | |
const desc = Object.getOwnPropertyDescriptor(context, prop) | |
if (desc) { | |
Object.defineProperty(context, prop, { | |
set(value) { | |
resolve(value) | |
desc.set(value) | |
} | |
}) | |
} else { | |
let targetProperty | |
Object.defineProperty(context, prop, { | |
get() { | |
return targetProperty | |
}, | |
set(value) { | |
targetProperty = value | |
resolve(value) | |
}, | |
configurable: true | |
}) | |
} | |
}) | |
const waitForPath = path => path | |
.split('.') | |
.reduce( | |
(acc, cur) => acc | |
.then(ctx => waitForProp(cur, ctx)), | |
Promise.resolve(window) | |
) | |
waitForPath('zzz.xxx.mmm').then(() => { console.log('aaa') }) | |
waitForPath('zzz.xxx').then(() => { console.log('bbb') }) | |
waitForPath('zzz').then(() => { console.log('ccc') }) | |
setTimeout(() => { window.zzz = { xxx: { mmm: true }} }, 1000) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment