Last active
August 30, 2020 13:35
-
-
Save designerzen/8510c5f53be2b15dd61556681f904fb3 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// 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