Skip to content

Instantly share code, notes, and snippets.

@devnix
Created February 7, 2017 17:24
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 devnix/9e99c8ba2a249711348e561e490e7341 to your computer and use it in GitHub Desktop.
Save devnix/9e99c8ba2a249711348e561e490e7341 to your computer and use it in GitHub Desktop.
CommonJS DOM-based Routing
window.App = {
common: require('./app/Common'),
HomeController: require('./app/Controllers/HomeController'),
};
var UTIL = {
exec: function (controller, action) {
var ns = App, // Change the namespace
action = (action === undefined) ? "init" : action;
if (controller !== '' && ns[controller] && typeof ns[controller][action] == 'function') {
ns[controller][action]();
}
},
init: function() {
var body = document.body,
controller = body.getAttribute('data-controller'),
action = body.getAttribute('data-action');
UTIL.exec('common');
UTIL.exec(controller);
UTIL.exec(controller, action);
UTIL.exec('common', 'finalize');
}
};
$(document).ready(UTIL.init);
(function() {
'use strict'
// Constructor
function Common() {
// Example of calling to a private method from the constructor
_foo();
}
// Public methods
Common.prototype.init = function() {
console.log('App.common.init()');
};
Common.prototype.finalize = function() {
console.log('App.common.finalize()');
};
// Private methods
function _foo() {
}
// Export
module.exports = new Common;
})();
(function() {
'use strict';
// Constructor
function HomeController() {
}
// Public methods
HomeController.prototype.init = function() {
console.log('HomeController.common.init()');
};
HomeController.prototype.index = function() {
console.log('HomeController.common.index()');
};
HomeController.prototype.delete = function() {
console.log('HomeController.common.delete()');
};
// Private methods
// Export
module.exports = new HomeController;
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment