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.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
doublejosh
  • 5,548
  • 4
  • 39
  • 45

1 Answers1

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.

gilly3
  • 87,962
  • 25
  • 144
  • 176
  • You probably should return the value of calling the oldVersion in case the return value is important. – jfriend00 Nov 10 '11 at 00:05
  • 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 Dec 23 '11 at 00:20
  • 1
    @doublejosh - I didn't see your comment until just now. I've updated my answer to address your comment. – gilly3 Feb 27 '12 at 22:08
  • 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) ? – Cystack Dec 29 '13 at 20:54
  • @Cystack - If your function is a click event handler, why not just listen for the click event? I can conceive of weird circumstances where this could have strange effects, but they seem unlikely. Context (`this`) is handled by using `.apply()`, and this is safe. – gilly3 Dec 31 '13 at 05:18
  • I know this is fairly old, but does this logic still apply? Also, would doing this (rewriting functions) on a larger scale significantly reduce page performance or load time? – Jody Heavener May 18 '14 at 05:24
  • 1
    @JodyHeavener - In general, yes, the logic still applies. And, no, I wouldn't expect it to have a performance impact. – gilly3 May 18 '14 at 08:25
  • Works great for SharePoint functions too! – TadLewis Jan 26 '18 at 23:05