Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save trigun0x2/7ec99180b5d257d150ba to your computer and use it in GitHub Desktop.
Save trigun0x2/7ec99180b5d257d150ba to your computer and use it in GitHub Desktop.
Per-view JavaScript functions for Phoenix. Keeps things out of global space, allows a page to specifically invoke the JS it needs.
import {Socket} from "phoenix";
let socket = new Socket("/ws");
let App = {
mainPage: function(data){
console.log(data);
},
anotherPage: function(data){
console.log(data);
}
};
// Look for any onload messages, give it the App
// context
if(window.appConfig !== undefined) {
window.appConfig.onLoad.call(this, App);
}
<body>
<div class="container">
<div class="header">
<h1>YourApp</h1>
</div>
<main>
<%= @inner %>
</main>
<div class="footer">
</div>
</div> <!-- /container -->
<script src="<%= static_path(@conn, "/js/app.js") %>"></script>
<script>require("web/static/js/app")</script>
</body>
<h1>Hello</h1>
<script>
window.appConfig = {
onLoad: function(App) {
App.mainPage({
id: "<%= @id %>",
thing: "wat",
anotherThing: "AlsoWat"
});
}
};
</script>
How to load page-specific JS functions and pass values to those functions when JS is loaded below your views.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment