Last active
February 4, 2017 16:16
-
-
Save jonatanklosko/a4c2df8a0eae64289eec to your computer and use it in GitHub Desktop.
Rails 4 and JavaScript assets
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- app/views/layouts/application.html.erb --> | |
<!-- ... --> | |
<body class="<%= controller_name %> <%= action_name %>"> | |
<!-- ... --> | |
</body> | |
<!-- ... --> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# app/assets/javascript/page_specific.coffee | |
onPage 'users create, users edit', -> | |
# Pages specific code goes here |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# app/assets/javascript/universal.coffee | |
onEveryPage -> | |
# Code available on every page goes here. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Note: the new version of turbolinks (turbolinks 5) uses different event names, so both
'page:change'
should be replaced byturbolinks:load
.