Created
August 22, 2012 18:24
-
-
Save tuzz/3428142 to your computer and use it in GitHub Desktop.
A modular approach to writing behavioural JavaScript for a web application
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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