Function listener in javascript and/or jQuery

2020-08-13 03:21发布

问题:

Wondering if there is an elegant way to listen for a function in javascript and/or jQuery.

Rather than listening for a $('#mything').click(function(){ //blah }) I'd like to listen for when a specific function is fired off. I don't want to edit the function as it's within a library that I don't want to hack directly.

I did find this: http://plugins.jquery.com/project/jqConnect which connects functions.

But wondering about a better technique.

回答1:

The only way to do this is to override the function (ie, hack the library):

(function() {
    var oldVersion = someLibrary.someFunction;
    someLibrary.someFunction = function() {
        // do some stuff
        var result = oldVersion.apply(this, arguments);
        // do some more stuff
        return result;
    };
})();

Edit: To run your code after the library function has run, just call the library function first, storing the result in a variable. Then, run your code, and finally return the previously stored result. I've updated my example above to accomodate running code either before or after the library function.