Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function listener in javascript and/or jQuery

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.

like image 627
doublejosh Avatar asked Nov 09 '11 23:11

doublejosh


People also ask

What is jQuery listener?

In JavaScript, these things that happen are called DOM events and the code written to trigger the action is called an event listener or event handler.

What is JavaScript and listener?

An event listener is a procedure in JavaScript that waits for an event to occur. The simple example of an event is a user clicking the mouse or pressing a key on the keyboard.

What is the difference between JavaScript and jQuery?

JavaScript is an independent language and can exist on its own. JQuery is a JavaScript library. It would not have been invented had JavaScript was not there. jQuery is still dependent on JavaScript as it has to be converted to JavaScript for the browser in-built JavaScript engine to interpret and run it.

What is the function of listeners?

The listener is programmed to react to an input or signal by calling the event's handler. The term event listener is often specific to Java and JavaScript. In other languages, a subroutine that performs a similar function is referred to as an event handler.


1 Answers

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.

like image 180
gilly3 Avatar answered Oct 19 '22 01:10

gilly3