Skip to content

Instantly share code, notes, and snippets.

@tuzz
Created August 22, 2012 18: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 tuzz/3428142 to your computer and use it in GitHub Desktop.
Save tuzz/3428142 to your computer and use it in GitHub Desktop.
A modular approach to writing behavioural JavaScript for a web application
// Dependencies: jQuery
// Declare a namespace object for your application to avoid clobbering global variables.
var MyNamespace = {};
// Define a 'loader' method that attaches modular functions to DOM elements.
MyNamespace.loader = function (el) {
$('[data-module]', el).each(function () {
var module = $(this).data('module').split(','),
that = this;
$.each(module, function (i, name) {
MyNamespace[name](that);
});
});
};
// Call loader on the root DOM element once it has loaded.
$(document).ready(function () {
MyNamespace.loader(document.documentElement);
});
// Attach data modules to DOM elements as required.
// <foo data-module="bar,baz"></foo>
// Define methods corresponding to the modules, that receive the element.
MyNamespace.bar = function(el) {
el.text("bar");
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment