Enhance event listener management in BasicScripts component
- Introduced a mechanism to store and remove event listeners, ensuring old listeners are cleared before new ones are attached. This improves performance and prevents potential memory leaks.
This commit is contained in:
@@ -31,16 +31,31 @@ import { UI } from 'astrowind:config';
|
||||
};
|
||||
initTheme();
|
||||
|
||||
// Store event listeners so they can be removed and re-attached
|
||||
let eventListeners = [];
|
||||
|
||||
function removeAllEventListeners() {
|
||||
eventListeners.forEach(({ element, event, handler }) => {
|
||||
element.removeEventListener(event, handler);
|
||||
});
|
||||
eventListeners = [];
|
||||
}
|
||||
|
||||
function attachEvent(selector, event, fn) {
|
||||
const matches = typeof selector === 'string' ? document.querySelectorAll(selector) : selector;
|
||||
if (matches && matches.length) {
|
||||
matches.forEach((elem) => {
|
||||
elem.addEventListener(event, (e) => fn(e, elem), false);
|
||||
const handler = (e) => fn(e, elem);
|
||||
elem.addEventListener(event, handler, false);
|
||||
eventListeners.push({ element: elem, event, handler });
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const onLoad = function () {
|
||||
// Remove old event listeners before attaching new ones
|
||||
removeAllEventListeners();
|
||||
|
||||
let lastKnownScrollPosition = window.scrollY;
|
||||
let ticking = false;
|
||||
|
||||
|
||||
Reference in New Issue
Block a user