This is a refined version of @AndrewHathaway's and @DannyLePage's javascript site pattern.
Has global methods, site wide methods, and page-specific methods.
This is a refined version of @AndrewHathaway's and @DannyLePage's javascript site pattern.
Has global methods, site wide methods, and page-specific methods.
| 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); |