Skip to content

Instantly share code, notes, and snippets.

@cargowire
Created December 17, 2010 12:42
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 cargowire/744876 to your computer and use it in GitHub Desktop.
Save cargowire/744876 to your computer and use it in GitHub Desktop.
Implements a simple json traverse as the only call in jQuery onReady to find all '_load' methods on classes and call them within their own scope. Allows easy adding of new 'classes' within that known namespace that control their own load and private vars
// Single jquery onload action covers all namespaced items
$(function () { traverse(myNamespace); });
// Identify all _load methods in the namespace and call them within their own object scope
var traverse = function(jsonObj, parentObj, name) {
if (typeof (jsonObj) == "object") {
parentObj = jsonObj;
$.each(jsonObj, function(k,v) {
traverse(v, parentObj, k);
});
} else if (typeof(jsonObj) == "function") {
if (name == "_load")
jsonObj.apply(parentObj);
}
}
/* An example namespace with a myItem 'class' and a simple load method attaching an event to a DOM element. privateMsgText is unavailable to external callers and must be set via setMessage method */
var myNamespace= {};
myNamespace.myItem = function () {
var privateAnchorId = 'test', privateMsgText = 'message!!';
return {
_load: function () {
var that = this;
$('#' + privateAnchorId ).click(function () {
that.showMessage(privateMsgText);
return false;
});
},
showMessage: function (msg) {
alert(msg);
},
setMessage: function (msg) {
privateMsgText = msg;
}
};
} ();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment