Skip to content

Instantly share code, notes, and snippets.

@napcs
Last active January 20, 2020 04:05
Show Gist options
  • Save napcs/c86ae7960d69ef59d259 to your computer and use it in GitHub Desktop.
Save napcs/c86ae7960d69ef59d259 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.
@trigun0x2
Copy link

What would be some cons for using this?

@ynjiun
Copy link

ynjiun commented Jun 24, 2018

This example is exactly what I need! Thank you so much for posting this. Great job!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment