Skip to content

Instantly share code, notes, and snippets.

@nathggns
Last active December 15, 2015 18:48
Show Gist options
  • Save nathggns/5306052 to your computer and use it in GitHub Desktop.
Save nathggns/5306052 to your computer and use it in GitHub Desktop.
Refined version of @andrewhathaway and @dannylepage's site module pattern.
var site = (function(window, document, undefined) {
// Methods for each page
var site_methods = {
home: function() {
},
about: function() {
}
};
// Private site wide methods
var site_wide = {
init: function(site) {
// Assign our site variable
this.site = site
// Run methods
this.some_method();
},
some_method: function() {
}
};
// Global methods
return {
init: function(page_name) {
// If page name hasn't been assigned, guess it.
if (typeof page_name === 'undefined') {
page_name = window.location.pathname.replace(/\/$/, '').match(/(.*)\/(.*)$/)[2];
}
// Set the page name
this.page_name = page_name;
// Call the page_load method when page has loaded
// Can easily replace this with jQuery.ready or whatever...
document.addEventListener('DOMContentLoaded', this.page_load);
},
page_load: function() {
// Get our method_name, by using the
// page_name replacing - with _, and lowercasing it
method_name = this.page_name.replace(/-/g, '_').toLowerCase();
// Assign the site variable to site_methods
site_methods.site = this;
// If we have a method for this page, call it
if (site_methods.hasOwnProperty(method_name)) {
site_methods[method_name]();
} else {
// No method set up for this page
}
// Run site_wide functions
site_wide.init(this);
}
};
}(this, this.document));
// Manually define page_name, or it will be undefined
// and the init function will guess using URL
site.init(window.page_name);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment