Skip to content

Instantly share code, notes, and snippets.

@46bit
Created September 3, 2012 05:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 46bit/3606848 to your computer and use it in GitHub Desktop.
Save 46bit/3606848 to your computer and use it in GitHub Desktop.
Page-specific Javascript under asset pipeline (Rails)
// Add this to your layout file as the <body> tag:
<body data-page="<%= "#{controller.controller_name}##{controller.method_name}" %>">
// Now save this to /app/assets/javascript/bootloader.js (requires jQuery):
var app = {
actions: [],
action: function (page, callback) {
this.actions[page] = this.actions[page] || [];
this.actions[page].push(callback);
return this;
},
run: function (page) {
for (var i in this.actions[page]) {
this.actions[page][i]();
}
return this;
}
};
$(document).ready(function () {
app.run($("body").attr("data-page"));
});
// Now utilise it in your Javascript files for particular pages like follows:
app.action("books#new", function () {
// Javascript to run upon load of /books/new page goes here
console.log("On /books/new.");
}).action("books#show", function () {
// Javascript to run upon load of /books/show page goes here
console.log("On /books/show.");
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment