Skip to content

Commit

Permalink
fix: Prevent updateExpandedHeight() from running after being destroyed
Browse files Browse the repository at this point in the history
This was causing “max-height” to be set to 0px
  • Loading branch information
tedw committed Feb 14, 2019
1 parent 04bf49e commit 4a0da91
Showing 1 changed file with 18 additions and 10 deletions.
28 changes: 18 additions & 10 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,8 @@ export default class ExpandToggle extends EventEmitter {
}

init() {
// Store state to avoid calling resize handler after component has been destroyed
this.isActive = true;
// Accessibility setup
this.el.setAttribute("aria-haspopup", true);
this.el.setAttribute("aria-expanded", false);
Expand Down Expand Up @@ -114,6 +116,13 @@ export default class ExpandToggle extends EventEmitter {
}

destroy() {
this.isActive = false;

// Remove event listeners
this.el.removeEventListener("click", this.clickHandler);
this.el.removeEventListener("keydown", this.keydownHandler);
window.removeEventListener("resize", this.resizeHandler);

// Remove aria attributes
this.el.removeAttribute("aria-haspopup");
this.el.removeAttribute("aria-expanded");
Expand All @@ -135,10 +144,6 @@ export default class ExpandToggle extends EventEmitter {
this.targetEl.classList.remove(...this.expandedClasses);
}

// Remove event listeners
this.el.removeEventListener("click", this.clickHandler);
this.el.removeEventListener("keydown", this.keydownHandler);

this.emitEvent("destroy");
}

Expand All @@ -159,13 +164,16 @@ export default class ExpandToggle extends EventEmitter {
// Set max-height to the expanded height so we can animate it.
this.updateExpandedHeight();

this.resizeHandler = debounce(event => {
// Due to debounce() it’s possible for this to run after destroy() has been called.
// To avoid this edge case, check “this.isActive” first.
if (this.isActive) {
this.updateExpandedHeight();
}
}, 100).bind(this);

// Update target element’s max-height on resize
window.addEventListener(
"resize",
debounce(function(event) {
self.updateExpandedHeight();
}, 150)
);
window.addEventListener("resize", this.resizeHandler);
}

// Set max-height of target element to its expanded height without triggering relayout.
Expand Down

0 comments on commit 4a0da91

Please sign in to comment.