Skip to content

Instantly share code, notes, and snippets.

@jonatanklosko
Last active February 4, 2017 16:16
Show Gist options
  • Save jonatanklosko/a4c2df8a0eae64289eec to your computer and use it in GitHub Desktop.
Save jonatanklosko/a4c2df8a0eae64289eec to your computer and use it in GitHub Desktop.
Rails 4 and JavaScript assets
<!-- app/views/layouts/application.html.erb -->
<!-- ... -->
<body class="<%= controller_name %> <%= action_name %>">
<!-- ... -->
</body>
<!-- ... -->
// app/assets/javascript/application.js
/* require... */
//= require_self
//= require_tree .
// Executes the given function on the specified page/pages.
// Requires body to have class '<controller> <action>'.
// The given pageSelector should have a format: '<controller> <action>'.
// Could be followed by comma and another pageSelector.
// Example: 'users show, users edit, users update, sessions new'.
function onPage(pageSelector, fun) {
pageSelector = pageSelector.replace(/, /g, ',.')
.replace(/ /g, '.')
.replace(/^/, '.');
$(document).on('page:change', function() {
if ($(pageSelector).length > 0) {
fun();
}
});
};
// Executes the given function on every page.
function onEveryPage(fun) {
$(document).on('page:change', fun);
}
# app/assets/javascript/page_specific.coffee
onPage 'users create, users edit', ->
# Pages specific code goes here
# app/assets/javascript/universal.coffee
onEveryPage ->
# Code available on every page goes here.
@jonatanklosko
Copy link
Author

Note: the new version of turbolinks (turbolinks 5) uses different event names, so both 'page:change' should be replaced by turbolinks:load.

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