Skip to content

Commit

Permalink
Unload the current route script safely
Browse files Browse the repository at this point in the history
  • Loading branch information
Quetzacoalt91 committed Nov 18, 2024
1 parent 744e465 commit 6704cb8
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 0 deletions.
11 changes: 11 additions & 0 deletions _dev/src/ts/routing/ScriptHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,4 +68,15 @@ export default class ScriptHandler {
this.#currentScript?.beforeDestroy();
this.#loadScript(newRoute);
}

/**
* @public
* @returns void
* @description Unloads the currently loaded script.
* Should be called before updating the DOM.
*/
public unloadRouteScript(): void {
this.#currentScript?.beforeDestroy();
this.#currentScript = undefined;
}
}
4 changes: 4 additions & 0 deletions _dev/src/ts/utils/Hydration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,10 @@ export default class Hydration {
const elementToUpdate = document.getElementById(data.parent_to_update);

if (elementToUpdate && data.new_content) {
if (data.new_route) {
scriptHandler.unloadRouteScript();
}

elementToUpdate.innerHTML = data.new_content;

if (data.new_route) {
Expand Down
7 changes: 7 additions & 0 deletions _dev/tests/utils/Hydration.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import ScriptHandler from '../../src/ts/routing/ScriptHandler';

const setNewRouteMock = jest.spyOn(RouteHandler.prototype, 'setNewRoute');
const updateRouteScriptMock = jest.spyOn(ScriptHandler.prototype, 'updateRouteScript');
const unloadRouteScriptMock = jest.spyOn(ScriptHandler.prototype, 'unloadRouteScript');

jest.mock('../../src/ts/pages/HomePage', () => {
return jest.fn().mockImplementation(() => {
Expand Down Expand Up @@ -159,12 +160,18 @@ describe('Hydration and scripts lifecycle', () => {
};
hydration.hydrate(initialResponse);

expect(setNewRouteMock).toHaveBeenCalledTimes(1);
expect(unloadRouteScriptMock).toHaveBeenCalledTimes(1);

const nextResponse: ApiResponseHydration = {
hydration: true,
new_content: `<p>New Content</p>`,
parent_to_update: 'parent',
new_route: 'home-page'
};
hydration.hydrate(nextResponse);

expect(setNewRouteMock).toHaveBeenCalledTimes(2);
expect(unloadRouteScriptMock).toHaveBeenCalledTimes(2);
});
});

0 comments on commit 6704cb8

Please sign in to comment.