Skip to content

Commit

Permalink
Update media attribute implementation to remove event handler when
Browse files Browse the repository at this point in the history
media attribute is updated, set to empty string, or removed.
  • Loading branch information
prushforth committed Dec 13, 2024
1 parent 7958e45 commit 5b49b19
Showing 1 changed file with 20 additions and 10 deletions.
30 changes: 20 additions & 10 deletions src/map-link.js
Original file line number Diff line number Diff line change
Expand Up @@ -373,20 +373,30 @@ export class HTMLLinkElement extends HTMLElement {
}
}
_registerMediaQuery(mq) {
if (!this._changeHandler) {
// Define and bind the change handler once
this._changeHandler = () => {
this.disabled = !this._mql.matches;
};
}

if (mq) {
let map = this.getMapEl();
if (!map) return;

// Remove listener from the old media query (if it exists)
if (this._mql) {
this._mql.removeEventListener('change', this._changeHandler);
}

// Set up the new media query and listener
this._mql = map.matchMedia(mq);
const changeHandler = () => {
if (this._mql.matches) {
this.enableLink();
} else {
this.disableLink();
}
};
changeHandler.bind(this);
changeHandler();
this._mql.addEventListener('change', changeHandler);
this._changeHandler(); // Initial evaluation
this._mql.addEventListener('change', this._changeHandler);
} else if (this._mql) {
// Clean up the existing listener
this._mql.removeEventListener('change', this._changeHandler);
delete this._mql;
}
}
_createAlternateLink(mapml) {
Expand Down

0 comments on commit 5b49b19

Please sign in to comment.