Skip to content

Instantly share code, notes, and snippets.

@stevegreatrex
Created January 5, 2017 17:05
Show Gist options
  • Save stevegreatrex/3b104c3c6fc653168577273b9bee2f08 to your computer and use it in GitHub Desktop.
Save stevegreatrex/3b104c3c6fc653168577273b9bee2f08 to your computer and use it in GitHub Desktop.
Cleaning up resources with MutationObserver: With MutationObserver
class MyD3Component {
constructor(targetElement: HTMLElement) {
//create some resources that need to be cleaned up
const observer = new MutationObserver(mutations => {
//get a flattened list of all removed elements
const removedElements = mutations.map(m => m.removedNodes)
.reduce((a, b) => a.concat(Array.prototype.slice.apply(b)), []);
//dispose if my target element was removed
if (removedElements.indexOf(targetElement) !== -1)
this.dispose();
});
observer.observe(targetElement.parentNode, { childList: true });
}
dispose() {
//clean up my resources
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment