cvoep28
cvoep28

Reputation: 423

How to attach event listener to a method in javascript

I know the following works for click events:

$("#element").click(function () {
  //logic here
});

But what if, instead of listening for a click, I want to listen if a method I created myself has been called?

So if I have a method like this:

function onDataReceived(data) {
   return data;
}

Is there a way to attach a listener to it and grab data when it's called? (in this case, data would either be a 1 or a 0, so I would be listening for onDataReceived(1) or onDataReceived(0).

Upvotes: 0

Views: 166

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075755

No, there isn't. You'd need to implement the method such that it supported notifying listeners. Naturally, you wouldn't do this just for one method, you'd give yourself an infrastructure for it. Look into pub/sub and similar libraries.

If you only need to do this as a one-off for debugging or similar, you can wrap the method, that's easily done:

var originalMethod = onDataReceived;
onDataReceived = function(data) {
    // ...do whatever you want with data here...
    return originalMethod.apply(this, arguments); // 'arguments' looks like pseudo-code, but it isn't
};

Now, calling onDataReceived calls your new method, which does something with data and then chains to the original.

Upvotes: 1

Related Questions