Skip to content

Instantly share code, notes, and snippets.

@gilbox
Last active August 29, 2015 14:03
Show Gist options
  • Save gilbox/b2b2542369df28c09b90 to your computer and use it in GitHub Desktop.
Save gilbox/b2b2542369df28c09b90 to your computer and use it in GitHub Desktop.
Function tracking for console debugging
/**
* Track a function attached to an object.
* For example to track: myObject.myFunc()
* trackFn(myObject, 'myFunc');
*
* You can also track multiple functions at once:
* trackFn(myObject, ['myFunc1','myFunc2','myFunc3']);
*
* optionally set st=true to get a stack trace
* optionally you can supply a msg argument
*/
window.trackFnThis = {};
function trackFn(obj, prop, st, msg) {
if (Array.isArray(prop)) {
prop.forEach(function(v) { trackFn(obj,v,st,msg); });
return;
}
var fn = obj[prop];
var m = (msg||'')+(msg?'.':'')+prop;
if (fn.__trackingFn__) { console.log("("+m+": We were already tracking this, updating the tracker.)"); fn = fn.__trackingFn__; }
tFn = function() {
window.trackFnThis[m] = this;
console.log.apply(console,['(trackFn)',m+':'].concat(arguments));
if (st) console.log((new Error).stack.match(/^.+$/mg).slice(2).join("\n"));
return fn.apply(obj, arguments);
};
tFn.__trackingFn__ = fn;
obj[prop] = tFn;
}
/**
* Performs deep traverse through object and
* tracks all functions it finds along the way
*/
function trackObjectFns(obj, st, msg, objs) {
objs = objs || [];
if (objs.indexOf(obj) != -1) return; // prevent infinite recursion
objs.push(obj);
try {
for (p in obj) {
var m = [msg||'',p].join('.');
if (typeof obj[p] == 'object') {
trackObjectFns(obj[p],st, m, objs);
}
if (typeof obj[p] == 'function') {
trackFn(obj, p, st, m);
}
}
} catch (e) {
console.warn('(trackObjectFns) Failed to traverse an object ',e)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment