使用jsdoc记录回调的正确方法是什么? [英] What's the proper way to document callbacks with jsdoc?
问题描述
我花了很长时间在互联网上寻找使用jsdoc正确记录回调的最佳方法,但遗憾的是,我还没有找到一个好的回复。
I've spent quite a while scouring the internet looking for the best way to properly document callbacks with jsdoc, but unfortunately, I haven't found a great one yet.
这是我的问题:
我正在为开发人员编写Node.js库。该库提供了开发人员将使用的多个类,函数和方法。
I'm writing a Node.js library for developers. This library provides multiple classes, functions, and methods that developers will be working with.
为了使我的代码清晰易懂,以及(希望)自动 - 在将来生成一些API文档,我已经开始在我的代码中使用 jsdoc 来自我记录正在发生的事情。
In order to make my code clear and understandable, as well as to (hopefully) auto-generate some API documentation in the future, I've started using jsdoc in my code to self-document what's happening.
假设我定义了如下函数:
Let's say I define a function like the following:
function addStuff(x, y, callback) {
callback(x+y);
});
使用jsdoc,我目前正在记录此函数,如下所示:
Using jsdoc, I'm currently documenting this function as follows:
/**
* Add two numbers together, then pass the results to a callback function.
*
* @function addStuff
* @param {int} x - An integer.
* @param {int} y - An integer.
* @param {function} callback - A callback to run whose signature is (sum), where
* sum is an integer.
*/
function addStuff(x, y, callback) {
callback(x+y);
});
我觉得上面的解决方案有点像hack-ish,因为我无法指定绝对术语回调函数应该接受什么。
I feel like the above solution is kinda hack-ish, since there's no way for me to specify in absolute terms what the callback function should accept.
理想情况下,我想做类似的事情:
Ideally, I'd like to do something like:
/**
* Add two numbers together, then pass the results to a callback function.
*
* @function addStuff
* @param {int} x - An integer.
* @param {int} y - An integer.
* @param {callback} callback - A callback to run.
* @param {int} callback.sum - An integer.
*/
function addStuff(x, y, callback) {
callback(x+y);
});
以上看起来似乎允许我更简单地传达我的回调需要接受的内容。这有意义吗?
The above seems like it'd allow me to more simply convey what my callback needs to accept. Does that make sense?
我想我的问题很简单:用jsdoc清楚地记录我的回调函数的最佳方法是什么?
I guess my question is simple: what's the best way to clearly document my callback functions with jsdoc?
感谢您的时间。
推荐答案
JSDoc 3有 @ callback标签就是为了这个目的。这是一个用法示例:
JSDoc 3 has a @callback tag for exactly this purpose. Here's a usage example:
/**
* Callback for adding two numbers.
*
* @callback addStuffCallback
* @param {int} sum - An integer.
*/
/**
* Add two numbers together, then pass the results to a callback function.
*
* @param {int} x - An integer.
* @param {int} y - An integer.
* @param {addStuffCallback} callback - A callback to run.
*/
function addStuff(x, y, callback) {
callback(x+y);
}
这篇关于使用jsdoc记录回调的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!