Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all arguments of a callback function

Tags:

Very often, I find myself using a callback function and I don't have its documentation handy, and it would be nice to see all of the arguments that are meant to be passed to that callback function.

// callback is a function that I don't know the args for... // and lets say it was defined to be used like: callback(name, number, value) something.doSomething( callback ); 

How can I determine what args its passing into that?

Note: looking at the source code can be unhelpful when the code itself is obfuscated and minified (as many js frameworks are)

like image 926
Kristian Avatar asked Mar 22 '12 18:03

Kristian


People also ask

Can callback function have arguments?

A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action. The above example is a synchronous callback, as it is executed immediately.

What are the parameters passed to a callback?

A JavaScript Callback Function is a function that is passed as a parameter to another JavaScript function, and the callback function is run inside of the function it was passed into. JavaScript Callback Functions can be used synchronously or asynchronously.

Does callback function have return statement?

No, callback should not be used with return.

How do you pass parameters in callback function in react?

Passing the event object of react as the second argument. If you want to pass a parameter to the click event handler you need to make use of the arrow function or bind the function. If you pass the argument directly the onClick function would be called automatically even before pressing the button.


2 Answers

To get the list of arguments without breaking functionality, overwrite the callback function in this way:

var original = callback; callback = function() {     // Do something with arguments:     console.log(arguments);     return original.apply(this, arguments); }; 
  1. The context, this is preserved.
  2. All arguments are correctly passed.
  3. The return value is correctly passed.

NOTE: This method works in most cases. Though there are edge cases where this method will fail, including:

  • Read-only properties (e.g. defined using Object.defineProperty with writable:false)
  • Properties that are defined using getters/setters, when the getter/setter is not symmetric.
  • Host objects and plugin APIs: E.g. Flash and ActiveX.
like image 110
Rob W Avatar answered Sep 19 '22 01:09

Rob W


Could it be as easy as

function callback() {     console.log(arguments); } 

?

Every function provides the arguments it has been called with in the automagic arguments collection.

like image 41
Tomalak Avatar answered Sep 19 '22 01:09

Tomalak