Search code examples
javascriptjquerybindobserver-patternnotify

jQuery/Javascript get notified when a function is executed


var f = function() {
    // Do something useful here
};

Is there a way to 'observe' this function, and get notified when it is executed? Something similar to bind in jQuery, but I want to bind functions and not dom events?

I don't want something like this:

var f = function() {
    // Do something useful here
    notifyObserver();
};

but I want something like this:

f.bind(function() {
    alert('F was executed.');
});

Solution

  • You could replace f with a function that calls notifyObserver:

    f = (function(oldF){
          return function(){
            notifyObserver(); 
            oldF(); 
          }; 
        })(f);
    

    That way you don't need to modify (the old) f itself. This doesn't include your bind functionality, of course. I'd probably create some kind of manager class for this where you can register event handlers

    manager.bind('f', function(){...});
    

    And creating the wrapper function would look more like

    f = (function(oldF){
          return function(){
            manager.notify('f');
            oldF(); 
          }; 
        })(f);
    

    You can generalize the creation of the wrapper:

    function wrap(methodToWrap, eventName){
        return function(){
            manager.notify(eventName);
            return methodToWrap.apply(this, arguments);
        }
    }
    

    (This works with any number of arguments and return values!)

    And then do something like:

    f = wrap(f, "f");
    

    See: http://jsfiddle.net/NBefc/2/ (updated, no with return values)