Commenting Callback Functions

Just wondering what a good way to comment on what parameters will be passed to the callback function.

Suppose we have the following code and incomplete comments

/** * an utterly useless function * * @param {String} an useless string * @param {Boolean} an useless boolean * @param {Function} ??? */ function Useless (str, bool, callback) { callback(str, bool); } 

What a good way to tell if a callback with str and bool parameters will be called?

+6
source share
3 answers

Usually, you simply record a function call with the names of the speakers:

 /* * @param {String} input: the text * @param {Function} callback(output, hasChanged): called after calculation */ 

Or, if the parameters need explanation, you can use a multi-line description:

 /* * @param {String} input: the text * @param {Function} callback(result, change) the function that is called after calculation result {String}: the output of the computation change {Bool}: whether a change has occured */ 
+4
source

I do not know of any agreements for this. I would just use:

 @param {Function} Called on success with the response (string) as the first param and the status code (int) as the second 

I know this is pretty verbose.

Another option would do it this way (similar to how jQuery does it, not in the code I know about, but in their documentation)

 @param {Function} onSuccess(response, statusCode) 

Here is an example http://api.jquery.com/jQuery.ajax/ This, of course, differs in that it is an options object, and the documentation has a different structure than the built-in documentation. But look at the callbacks and you will see the similarities.

For clarity, it is also much better to use a callback (response, statusCode) than callback (string, int). If you need to choose the one that is. The value before the type.

+2
source

Well, there are many ways to add comments in javascript; Here is my recommendation .

using // better than /* */ because then you can use the latter to pull out the whole block containing other comments. However, if you want to use the automated documentation tool, you should use comments similar to the javaDoc style.

This is an example that will work with YUI DOC (best) http://developer.yahoo.com/yui/yuidoc/#start

 /** * This is a description * @namespace My.Namespace * @method myMethodName * @param {String} str - some string * @param {Object} obj - some object * @param {requestCallback} callback - The callback that handles the response. * @return {bool} some bool */ function SampleFunction (str, obj, callback) { var isTrue = callback(str, obj); // do some process and returns true/false. return isTrue ; } 

Other parameters Examples: - http://usejsdoc.org/tags-param.html

Hope this helps you :)

0
source

Source: https://habr.com/ru/post/922005/


All Articles