adamghill / django-unicorn

The magical reactive component framework for Django ✨
https://www.django-unicorn.com
MIT License
2.37k stars 120 forks source link

<script> sections not being called when component is late rendered #436

Closed martindemello closed 2 years ago

martindemello commented 2 years ago

I have several components of the form

  <div>
    {{ round_pairing | json_script:"round-pairings-data" }}
    <div unicorn:ignore id="tabulator-table"></div>
    <script src="{% static "tournament/round_pairings.js" %}"></script>
  </div>

which load data for a table and then call a javascript function to populate it in the tabulator-table div. The javascript file is different for each component, and calls makeTable() at top level at the end.

This works fine when I include a component directly in a page. Now I'm trying to write a tab view, with the parent looking like

      <div>
          <a href="{% url 'tournament:round_pairings' tournament.id div.id %}"
            unicorn:click.prevent="set_active({{div.id}}, 'round-pairings')"
          >Round Pairings</a>
          {% if active_view %}
          {% unicorn active_view division=active_division parent=view key=active_key %}
          {% endif %}
      </div>

where active_view is the name of the child component, and it looks like the javascript is never getting loaded, and furthermore that any script tags in the child component are not getting executed.

I suspect this is the same issue as https://github.com/adamghill/django-unicorn/pull/243 and that there's no good solution, but filing this just in case there's been a fix or some better way of doing things.

adamghill commented 2 years ago

When poking around in the morphdom issues I found https://github.com/patrick-steele-idem/morphdom/issues/178. I wonder if adding these morphdom options would make this work as expected for script tags? If you want to try this out, the morphdom options are in https://github.com/adamghill/django-unicorn/blob/main/django_unicorn/static/unicorn/js/morphdom/2.6.1/options.js. I'll try it out in the next few days and see what happens. 👍

martindemello commented 2 years ago

thanks! i'm still getting to grips with the code but i'll give it a try and see if i can get anywhere. (i also filed #437 in the process of trying to find a different way to do things)

adamghill commented 2 years ago

https://github.com/adamghill/django-unicorn/pull/442 is one approach which will reload the script tag after a template has been morphed. I am going to hide it behind a setting for now, though.

adamghill commented 2 years ago

I have added a fix for this in 0.48.0. You can enable it with the RELOAD_SCRIPT_ELEMENTS setting.