Skip to content

How to re-instance a library

❓ Why do we need to re-instance libraries?

Section titled “❓ Why do we need to re-instance libraries?”

In Terra, we usually function within the bounds of the lifecycle of our swup application:

  • We instance our handlers when we first load our page, in Main.js
  • We listen in them for events at two points:
    • contentReplaced —> we entered a new page and the DOM has been replaced
    • willReplaceContent —> we are leaving a page and perform actions before loading the new one

This is usually enough for our purposes, but there are some edge cases where we need to be able to re-call our handlers so they can instance our libraries for us at specific points that do not match any of the above mentioned.

📍 Example: a filter changes and it needs to re-instance a Slider

Section titled “📍 Example: a filter changes and it needs to re-instance a Slider”

We can see this in action at our Stifel page, where all the transaction and team sliders depend on the filters available above them.

We make use of our event-based handlers to re-query them when needed.

In the handler of the library that needs to re-trigger the handlers (in this case, filters), we need to have a callback that acts when the action from the library is completed, and we will be emitting an event from this callback to flag to our application that we need to act:

handler/filters/Handler.js
constructor(payload) {
super(payload);
this.init();
this.events();
this.configTeam = {
//...other configuration
callback: {
onStart: () => {},
onComplete: () => {
this.emitter.emit("ReloadSliders")
},
},
};
}

We will listen for this event we are emitting on the handler that we are trying to reload, in this case, Slider:

handler/slider/Handler.js
this.emitter.on("ReloadSliders", async () => {
if (this.DOM.sliderElements.length) {
super.destroyInstances({ libraryName: "Slider" });
}
this.DOM = this.updateTheDOM; // Re-query elements each time this is called
super.assignInstances({
elementGroups: this.getConfigtype(),
});
});

And when we get that event, we will instruct our handler to destroy all present instances of the slider (so they don’t mash with the new ones), update the DOM (this is important, when we change the filters we are changing the DOM inside the results and the DOM that hosted our previous slider will not exist anymore) and assign instances again using our CoreHandler.