Skip to content

Instantly share code, notes, and snippets.

@pofigizm
Created August 8, 2017 19:35
Show Gist options
  • Save pofigizm/311d2390152bbe31f25867a8fca61ab2 to your computer and use it in GitHub Desktop.
Save pofigizm/311d2390152bbe31f25867a8fca61ab2 to your computer and use it in GitHub Desktop.
Waiting for define deep property in window object
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