Modal: refactor listeners to reduce some code noise (#35902)

This commit is contained in:
GeoSot 2022-03-01 17:08:12 +02:00 committed by GitHub
parent c644f09d88
commit 63f30ac8ee
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 10 additions and 23 deletions

View File

@ -69,6 +69,8 @@ class Modal extends BaseComponent {
this._isShown = false this._isShown = false
this._isTransitioning = false this._isTransitioning = false
this._scrollBar = new ScrollBarHelper() this._scrollBar = new ScrollBarHelper()
this._addEventListeners()
} }
// Getters // Getters
@ -111,9 +113,6 @@ class Modal extends BaseComponent {
this._adjustDialog() this._adjustDialog()
this._toggleEscapeEventListener(true)
this._toggleResizeEventListener(true)
this._backdrop.show(() => this._showElement(relatedTarget)) this._backdrop.show(() => this._showElement(relatedTarget))
} }
@ -130,10 +129,6 @@ class Modal extends BaseComponent {
this._isShown = false this._isShown = false
this._isTransitioning = true this._isTransitioning = true
this._toggleEscapeEventListener(false)
this._toggleResizeEventListener(false)
this._focustrap.deactivate() this._focustrap.deactivate()
this._element.classList.remove(CLASS_NAME_SHOW) this._element.classList.remove(CLASS_NAME_SHOW)
@ -217,12 +212,7 @@ class Modal extends BaseComponent {
this._queueCallback(transitionComplete, this._dialog, this._isAnimated()) this._queueCallback(transitionComplete, this._dialog, this._isAnimated())
} }
_toggleEscapeEventListener(enable) { _addEventListeners() {
if (!enable) {
EventHandler.off(this._element, EVENT_KEYDOWN_DISMISS)
return
}
EventHandler.on(this._element, EVENT_KEYDOWN_DISMISS, event => { EventHandler.on(this._element, EVENT_KEYDOWN_DISMISS, event => {
if (event.key !== ESCAPE_KEY) { if (event.key !== ESCAPE_KEY) {
return return
@ -236,15 +226,12 @@ class Modal extends BaseComponent {
this._triggerBackdropTransition() this._triggerBackdropTransition()
}) })
}
_toggleResizeEventListener(enable) { EventHandler.on(window, EVENT_RESIZE, () => {
if (enable) { if (this._isShown && !this._isTransitioning) {
EventHandler.on(window, EVENT_RESIZE, () => this._adjustDialog()) this._adjustDialog()
return
} }
})
EventHandler.off(window, EVENT_RESIZE)
} }
_hideModal() { _hideModal() {

View File

@ -438,10 +438,10 @@ describe('Modal', () => {
const modalEl = fixtureEl.querySelector('.modal') const modalEl = fixtureEl.querySelector('.modal')
const modal = new Modal(modalEl) const modal = new Modal(modalEl)
spyOn(modal, '_adjustDialog').and.callThrough() const spy = spyOn(modal, '_adjustDialog').and.callThrough()
const expectDone = () => { const expectDone = () => {
expect(modal._adjustDialog).toHaveBeenCalled() expect(spy).toHaveBeenCalled()
resolve() resolve()
} }