Created
September 3, 2012 05:11
-
-
Save 46bit/3606848 to your computer and use it in GitHub Desktop.
Page-specific Javascript under asset pipeline (Rails)
This file contains hidden or 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
// 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