Skip to content

Instantly share code, notes, and snippets.

@designerzen
Last active August 30, 2020 13:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save designerzen/8510c5f53be2b15dd61556681f904fb3 to your computer and use it in GitHub Desktop.
Save designerzen/8510c5f53be2b15dd61556681f904fb3 to your computer and use it in GitHub Desktop.
// This watches for a prop in three different ways to ensure that it eventually resolves
export const onRefAvailable = (reference, callback) => {
const hasReference = r => (r && r.value && r.value instanceof HTMLElement)
const test = (r=reference) => {
//console.error("testing for refs",r)
if ( hasReference(r) )
{
callback && callback(reference.value)
return true
}else{
return false
}
}
// first let's see if by somehow it is already available
test()
// secondly let's monitor the onMounted method
// let timer
onMounted(()=>{
// check to see if ref exists!
// if ( !test() )
// {
// // if watch never finds the ref...
// // let's also use a timer just in case nothing happens after a while...
// timer = setInterval(()=>{
// if ( test() )
// {
// clearInterval(timer)
// }
// }, 200)
// }
test()
})
// next let's watch the variable and hopefully before long it will materialise
const watcher = watch( reference, (element, prevElement, onCleanup) => {
if ( test(element) )
{
// kill the watch!
watcher()
}
})
onUnmounted(()=>{
watcher()
// kill the timer
clearInterval(timer)
// optionally call callback with null?
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment