addEventListener of null object JS error causes malfunctioning of phoenix form?!

I have a Phoenix form in a live component, and an event which is called when the form is submitted.

<%= f = form_for @changeset, "#", [phx_submit: "save", phx_target: @myself] %>
etc.

All works fine. Now, somewhere else in my application, I have added a plain Javascript addEventListener on some DOM object that is unrelated to my form. Also works fine.

If that DOM object does not exist, I get a console error saying something like Uncaught TypeError: Cannot read property 'addEventListener' of null. As expected.

But a side effect is that the “save” event on my form is not triggered anymore on submit. Instead, the application just applies a POST request to the route of view that contains the form!

It took me a while to find out that these two issues were related at all but after some debugging it is clear that they are.

So, I know how to avoid this problem, but I really would like to know what is happening behind the scenes. How is it possible that some live view events are not triggered anymore by some unrelated javascript elsewhere?

Probably you are doing the addEventListener call and the initialisation of LiveView in the same execution flow (i.e. not separated by an event, setTimeout, or similar). When the addEventListener throws a TypeError, it is uncaught and the exception bubbles up the stack to the root. No code in that flow is executed anymore.

A simplified example:

function setupEventListener() {
  throw new Error();
}

function setupLiveView() {
  console.log("Done");
}

setupEventListener();
setupLiveView();

You can probably deduce that “Done” will never be logged from this code. I suspect the similar is occurring in your code, albeit with more levels of indirection in between. If the LV setup code is not run, then I wouldn’t be surprised that the client side event handlers aren’t added and the regular form behaviour happens.

Mmm, it is a bit different. The addEventListener is executed quite early, i.e. when the application is started.
My application has a search field on the landing page. Results are shown in a live view, which works correctly. If you click on one of the results, it brings you to a different live view, which also works correctly. From there you can go to yet another liveview, with the form and the event that is not triggered. So there are quite some steps in between, with different live views which all have event handling. Only this one is not working.