public
Last active

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

  • Download Gist
Namespaced auto onload fired classes with jQuery
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
// 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;
}
};
} ();

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.