How to re-execute scripts in theme components

AI-generated summary

The discussion revolves around re-executing scripts in Discourse theme components when a route change occurs, without a full page refresh. Marvelxy initially asked how to achieve this, providing an example of re-rendering the footer to re-execute scripts.

michaeld suggested using api.onPageChange to execute code on page changes, providing an example code snippet.

However, Marvelxy encountered issues implementing this in their theme component and shared their code. osioke advised looking at prior art in other theme components for insights.

After taking osioke’s advice, Marvelxy discovered a relevant theme component (homepage-feature-component) that solved their issue. They thanked michaeld and osioke for their help.

Scripts in theme components execute only once; how do I re-execute them when there is a route change(not full page refresh)?

For example, I want the scripts in a component to execute even after navigating between tags.

<script type="text/discourse-plugin" version="0.8">
    api.onPageChange(() => {
        // your code
    });   
</script>

Where would this if I’m building a theme component? This is my code at the moment. I’m trying to re-render the footer every time there’s a route change so that the scripts would re-execute.

I’m getting weird errors.

I’m a total beginner, and I don’t know if this is the right way to go about this.

    initialize() {
      withPluginApi("0.8", api => {
        if (settings.Show_footer_on_login_required_page) {
          api.modifyClass("controller:static", {
            @on("init")
            showFooterOnStatic() {
              this.set("application.showFooter", true);
            }
        });

        api.onPageChange(() => {
          showFooterOnStatic() {
            this.set("application.showFooter", true);
          }
        });
      }
    });

Have you tried looking at prior art/work/code in another similar Customization > Theme component to get some insights on how to go about it?

I have looked at some, but they don’t seem to have what I’m trying to do. I guess I will look at more theme-component

Thanks, @osioke, and @michaeld :raised_hands:, I found exactly what I’ve been looking for after going through this theme-component: Homepage Feature

https://github.com/discourse/discourse-homepage-feature-component/blob/main/javascripts/homepage-featured-topics/connectors/above-main-container/homepage-featured-topics.js.es6