Skip to content

Instantly share code, notes, and snippets.

@dmitry-vsl
Created April 1, 2018 00:11
Show Gist options
  • Save dmitry-vsl/89b8ac16cad8fcc550bb402c55e8e197 to your computer and use it in GitHub Desktop.
Save dmitry-vsl/89b8ac16cad8fcc550bb402c55e8e197 to your computer and use it in GitHub Desktop.
Use mutation observer to build widget reacting on attaching/detaching to DOM
<script>
function DOMAttachWatcher(){
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
if([...mutation.addedNodes].includes(el) && onAttachCb){
onAttachCb()
}
if([...mutation.removedNodes].includes(el) && onDetachCb){
onDetachCb()
}
});
});
var config = {subtree: true, childList: true}
window.addEventListener('load', () => {
observer.observe(document.body, config);
})
// currently can watch just for one el
var el, onAttachCb, onDetachCb
function onAttach(_el, _cb){
el = _el
onAttachCb = _cb
}
function onDetach(_el, _cb){
el = _el
onDetachCb = _cb
}
return {onAttach, onDetach}
}
var {onAttach, onDetach} = DOMAttachWatcher()
function ClockWidget(){
var el = document.createElement('div')
function showTime(){
console.log('showTime')
el.textContent = new Date().toLocaleTimeString()
}
var interval
onAttach(el, () => {
interval = setInterval(showTime, 1000)
})
onDetach(el, () => {
clearInterval(interval)
})
return el
}
window.addEventListener('load', () => {
setTimeout(() => {
foo.appendChild(ClockWidget())
}, 1000)
setTimeout(() => {
foo.removeChild(foo.children[0])
}, 5000)
})
</script>
<body>
<div id='foo'></div>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment