I want to organize the use of socket
and Presence
in a template in my own way.
As a newbie, it seems to me that putting all the client code that deals with channels in sockets.js
can convert it into a very large piece.
Especially if there are many pages that use sockets / Presence.
I do not know which is the best solution (or if this is a problem for other people), but my misunderstood functioning of js, leads me to organize the code well.
In socket.js
import {Socket, Presence} from "phoenix"
// Other stuff
export {
Presence,
socket
}
In app.js
, instead of import socket from "./socket"
at teh end, I write
import {Presence, socket} from "./socket"
window.getPhoenixSocket = function () {
return socket;
};
window.getPhoenixPresence = function () {
return Presence;
};
And in the template eex
(I know it's not good practice to mix html and scripts) (except for the React guys!) I write the following script:
<script>
window.onload = function () {
let channel = getPhoenixSocket (). channel ("cute: channel", {})
let Presence = getPhoenixPresence ();
....
// Here I can use channel and Presence for my obscure purposes
....
}
</script>
Thus the code of each page that uses socket remains in the own page and not in socket.js
As I am not entirely satisfied with this solution, I ask you, is this correct? Is not it? What would be the best way to do it? Is there someone who has this problem?
===== EDIT ======
SOLUTION1:
A clear, intelligent, kind and complete response has been exposed by peerreynders at elixirforum
SOLUTION2:
Another solution, which Deini points to in Elixir-Lang's Slack Channel, using Webpack again, and involves much more Phoenix-Elixir style, has been published by hoang_nguyen on Medium.
SOLUTION3:
Using Brunch and using Webpack in Diacode and the second page here