Skip to content

Instantly share code, notes, and snippets.

@jhbabon
Created August 2, 2012 16:55
Show Gist options
  • Save jhbabon/3238660 to your computer and use it in GitHub Desktop.
Save jhbabon/3238660 to your computer and use it in GitHub Desktop.
Load javascript functions based on the current controller and action
-# Code...
%body{ :"data-controller" => controller_name, :"data-action" => action_name }
-# Code...
// Load the functions based on the action and controller of the page
// @link: http://viget.com/inspire/extending-paul-irishs-comprehensive-dom-ready-execution
var App = {
// Common actions for every page
'common': {
'init': function() { }
},
// Actions for the movies_controller
'movies': {
'init': function() { /* common code for movies */ },
'index': function() { alert('On movies'); },
'show': function() { alert('On a movie'); }
},
// Actions for the seasons_controller
'seasons': {
'init': function() { /* common code for seasons */ },
'index': function() { alert('On seasons'); },
'show': function() { alert('On a season'); }
}
};
// Object to load the functions based on the current controller an action
var Kernel = {
'exec': function(controller, action) {
var ns = App;
var action = (action === undefined) ? "init" : action;
if (controller !== "" &&
ns[controller] &&
typeof ns[controller][action] == "function") {
ns[controller][action]();
}
},
'init': function() {
var body = document.body;
var controller = body.getAttribute("data-controller");
var action = body.getAttribute("data-action");
Kernel.exec("common");
Kernel.exec(controller);
Kernel.exec(controller, action);
}
};
// Fire it!
$(document).ready(Kernel.init);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment