0

I'm keeping a record of each time various functions are called. I have a function called

record_activity( function_name );

I really don't want to have to write this at the top of every function I want to track. Currently there are lots of functions in the format:

Object.Key.Func = function() { ... }

I've written this, which seems to work but I'm really not sure about it's implications:

function sub ( variable, func ) {
    var temp_func = function ( args ) {
        record_activity( variable );
        return func.apply(this,arguments);
    }
    eval( variable + ' = ' + temp_func );
}

sub( 'Object.Key.Func', function (name) { alert('hi ' + name) } );
Object.Key.Func('test');

If there is a way of doing this without an eval I'd be much happier.

Thanks

Cosmicnet
  • 389
  • 4
  • 14
  • possible duplicate of [Javascript: How to set object property given its string name](http://stackoverflow.com/questions/13719593/javascript-how-to-set-object-property-given-its-string-name) – Felix Kling Sep 12 '13 at 11:17

1 Answers1

0

I think you can create a wrapper func for each func that you want to track. Hope the following code will help you:

var counter = {};
// assume this is what record_activity has to do.
function record_activity (f, func_name, args) {
    counter[func_name] = counter[func_name]===undefined ? 1 : counter[func_name]+1;
}

// assume that you want to keep track of functional call obj.foo and obj.bar
var obj = {
    a: 3,
    foo: function () {
        console.log("foo");
    },
    bar: function (b) {
        console.log("bar", this.a, b);
    }
};



function create_func (f, func_name) {
    return function () {
        record_activity(f, func_name, arguments);
        f.apply(obj, arguments);
    };
}
for(var prop in obj) {
    if (typeof obj[prop] === 'function') {
        // create the wrapper func
        obj[prop] = create_func(obj[prop], prop);
    }
};

// test
for (var i = 0; i < 3; i++) {
    obj.foo();
};
for (var i = 0; i < 10; i++) {
    obj.bar(i);
};

console.log(counter);
Wei Li
  • 471
  • 6
  • 14