Skip to content

Instantly share code, notes, and snippets.

@lukesutton
Created April 13, 2011 01:59
Show Gist options
  • Save lukesutton/916830 to your computer and use it in GitHub Desktop.
Save lukesutton/916830 to your computer and use it in GitHub Desktop.
// A specific controller and action
$S.init('users.index', function() {});
// All actions in Users
$S.init('users.*', function() {});
// All new actions in all controllers
$S.init('*.new', function() {});
// Everything all the time
$S.init('*.*', function() {});
// Multiple selectors (can be as many as you need)
$S.init('users.index', 'admins.index', function() {});
/*
* LOADER
* Executes a function based on the section -- indicated by the body
* id -- and the page -- indicated by the body class. This allows us to
* conditionally execute JS on a page without having to manually check for the
* existence of elements.
*/
var $S = {
_inits: {},
init: function() {
var args = Array.prototype.slice.call(arguments);
args.length > 2 ? this._forPages(args) : this._forPage(args[0], args[1]);
},
_forPage: function(section, fun) {
var parts = section.split('.');
if (parts[0] === '') {
var section = parts[1];
var page = '*';
}
else {
var section = parts[0];
var page = parts[1];
}
var entry = this._inits[section] || (this._inits[section] = {});
entry[page] || (entry[page] = []);
entry[page].push(fun);
},
_forPages: function(args) {
var fun = args.pop();
for (var i = 0; i < args.length; i++) { this._forPage(args[i], fun); }
},
load: function() {
var body = $(document.body);
var section = body.attr('id');
var page = body.attr('class');
this._fire(section, page);
this._fire('*', page);
},
_fire: function(section, page) {
var entry = $S._inits[section];
if (entry) {
var all = entry['*'], per = entry[page];
if (all) for (var i = 0; i < all.length; i++) { all[i](); }
if (per) for (var j = 0; j < per.length; j++) { per[j](); }
}
}
};
jQuery($.proxy($S, 'load'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment