Add hooks to socket *after* initialization?

I have been reading the JS interoperability guide and saw some examples on how to put custom hooks to be fired on some liveview events.

However I came up with the following question: Can a hook be defined into another js file which loads after app.js? This means, when socket is already connected and created so no constructor additions are possible.

You prrrrrrrobably could by mutating the hooks key but I certainly wouldn’t recommend it even if it works (and you didn’t hear that from me, lol). What are you looking to accomplish? Like, using something from a <script> tag?

1 Like

Thanks for answering!

I am trying to define hooks from other parts of the project (or even directly from dependencies), this way I could setup a dependency with its own html.heex (accomplished) and its liveview hooks if applicable (not accomplished, hence this question).

I also thought on generating the app.js file dynamically instead of a static file which might solve this issue, but I would prefer to avoid this approach.

You can certainly have them in separate files but you have to import them into app.js. I don’t think you’re gonna have much luck adding hooks at runtime. It’s been requested a couple of times before.

Ah yes, this is a known limitation. I don’t follow the dev mailing list closely but I think we should be getting a solution to this at some point. As it stands, any lib that includes JS hooks always has a step in the docs to import and splay them in, as per @cmo’s answer.

Surface has colocated hooks which it compiles into a single js file that you include. If you’re happy to write a compiler (or copy theirs) then this is an option.

The mailing list is just ads for weapons these days, ya gotta subscribe to the GitHub notifications (and be happy to delete 20 emails everyday).

lol, fair!

And yes, Surface has it so that is always an option. I honestly don’t love Surface so I never think to mention it. Or rather, I should say that I much prefer heex and very much appreciate the trailblazing Surface has done.

The first PR seems a lot interesting! It is a pitty that it got closed by Chris :frowning:

I think that for now it is better to generate tje app.js dynamically from a controller that will gather and include all hooks rather than add them later dynamically by manually patching.

Thanks to all for your responses!