3 ms·
Generally speaking, if it can be done in the client, it should be done in the client. Phoenix.LiveView.JS aims to tackle the obvious cases but it also document
by josevalim 4y ago
Generally speaking, if it can be done in the client, it should be done in the client.
Phoenix.LiveView.JS aims to tackle the obvious cases but it also documents a pattern that I tend to use a lot in my apps: https://hexdocs.pm/phoenix_live_view/Phoenix.LiveView.JS.html#module-custom-js-events-with-js-dispatch-1-and-window-addeventlistener https://hexdocs.pm/phoenix_live_view/Phoenix.LiveView.JS.htm...
The pattern above has a benefit that the dispatch still comes from Phoenix, so you are not relying on IDs or query selectors to attach functionality. You can see how we use it in Livebook here: https://github.com/livebook-dev/livebook/blob/main/assets/js/events.js https://github.com/livebook-dev/livebook/blob/main/assets/js.... However, if the callbacks get too complex, then you may indeed want to test them via headless browsers.
- mstipetic 4y agoHey Jose, funny to see there answering phoenix questions on a Saturday. Since we're discussing JS, are there any official plans to expose pushing events to the backend directly from JS? What I've been doing (and seen others do) is to assign a hook to a global window variable in the mounted callback, but that seems very hacky. Is there any reasons why that should be avoided or why you don't want to expose a proper API for that?
- josevalim 4y agoYou can do it using JS.push from the linked page. You can also use execJS to execute any JS event, including push, from anywhere. I am not sure if this helps though. :)
- foldr 4y agoYes indeed, my natural preference is to do it on the client – but then I can't figure out a way to unit test the behavior. I don't particularly love React overall, but it does make it easy to write tests for client-side UX logic without needing to use headless browsers. This is a fairly big deal, as headless browser tests are slow and cumbersome.