Skip to content

Commit

Permalink
Simplify MutationBasedRemovalTracker
Browse files Browse the repository at this point in the history
Stateless! It ReactTooltip#137-ready seamlessly.
  • Loading branch information
huumanoid committed Mar 28, 2017
1 parent d927d0e commit 3cc17b0
Showing 1 changed file with 16 additions and 26 deletions.
42 changes: 16 additions & 26 deletions src/decorators/trackRemoval.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,52 +47,40 @@ class MutationBasedRemovalTracker {

this.observer = null
this.inited = false
this.trackedElements = null
}

init () {
if (this.inited) {
this.unbind()
}

this.trackedElements = []
this.inited = true

const MutationObserver = getMutationObserverClass()
if (MutationObserver) {
this.observer = new MutationObserver(() => {
for (const element of this.trackedElements) {
if (this.isDetached(element) && element === this.tooltip.state.currentTarget) {
if (!MutationObserver) {
return
}

this.observer = new MutationObserver((mutations) => {
for (const mutation of mutations) {
for (const element of mutation.removedNodes) {
if (element === this.tooltip.state.currentTarget) {
this.tooltip.hideTooltip()
return
}
}
})
this.observer.observe(window.document, { childList: true, subtree: true })
}
}
})

this.inited = true
this.observer.observe(window.document, { childList: true, subtree: true })
}

unbind () {
if (this.observer) {
this.observer.disconnect()
this.observer = null
this.trackedElements = null
}
this.inited = false
}

attach (element) {
this.trackedElements.push(element)
}

// http://stackoverflow.com/a/32726412/7571078
isDetached (element) {
if (element.parentNode === window.document) {
return false
}
if (element.parentNode == null) return true
return this.isDetached(element.parentNode)
}
}

export default function (target) {
Expand All @@ -106,7 +94,9 @@ export default function (target) {
}

target.prototype.attachRemovalTracker = function (element) {
this.removalTracker.attach(element)
if (this.removalTracker.attach) {
this.removalTracker.attach(element)
}
}

target.prototype.unbindRemovalTracker = function () {
Expand Down

0 comments on commit 3cc17b0

Please sign in to comment.