11

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 Answer 1

11

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.

Sign up to request clarification or add additional context in comments.

8 Comments

You probably should return the value of calling the oldVersion in case the return value is important.
this is lovely, and totally works without having to hack the library... however this means by events have to occur BEFORE the library function runs. I'd like it to run THEN apply my checks and alterations.
@doublejosh - I didn't see your comment until just now. I've updated my answer to address your comment.
2 questions: if the function is anonymous (for example, it's a callback to a click listener), then there is no obvious way, right? Second question, is it 100% transparent or are there caveats I should be aware of when doing that (change of scope, this, sort of stuff) ?
@JodyHeavener - In general, yes, the logic still applies. And, no, I wouldn't expect it to have a performance impact.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.