JSDoc links to callback function - javascript

I have decided to use JSDoc to document a project I am working on. While reading the usage guide and questions here I still feel that I am not grasping some of the core concepts of JSDoc and I illustrated my incompetence in the following example: http://jsfiddle.net/zsbtykpv/
/**
* #module testModule
*/
/**
* #constructor
*/
var Test = function() {
/**
* #callback myCallback
* #param {Object} data An object that contains important data.
*/
/**
* A method that does something async
* #param {myCallback} cb a callback function
* #return {boolean} always returns true
*/
this.method = function(cb) {
doSomethingAsync(function(data) {
cb(data);
});
return true;
}
}
module.exports = Test;
Here, I have defined a module, indicated a constructor, and documented a method that takes a callback as one of its' parameters. Sounds pretty simple and appears to follow the guidelines set by the usage guide http://usejsdoc.org/.
But for some reason beyond my understanding (and that's probably the core concept I'm not getting), it shows the callback myCallback as a member of the testModule instead of the Test class. Shouldn't it default to be a member of the class and not the module? This also appears to prevent JSDoc from making a link to the callback definition, which is not a lot of fun.
Now I realize that if I were to write:
/**
* #callback module:testModule~Test~myCallback
* #param {Object} data An object that contains important data.
*/
/**
* A method that does something async
* #param {module:testModule~Test~myCallback} cb a callback function
* #return {boolean} always returns true
*/
I would get my desired behavior. But this seems to be a very clunky way of doing things and the generated links are far from pretty.
Sorry for the long buildup and thank you in advance for your help in my documentation effort :)

I have come across much the same problem. If you want nicer-looking links, you can always add a {#link} in the description and just use the canonical name in the #type like this:
/**
* #callback module:testModule~Test~myCallback
* #param {Object} data An object that contains important data.
*/
/**
* #param {myCallback} cb {#link module:testModule~Test~myCallback|myCallback}: a callback function
* #return {boolean} always returns true
*/
I realize that's a bit more frustrating to type, but it documents myCallback as a member of the class rather than the module, and the link looks nice.
If you really want the link in the #type and you don't care about how it documents the callback, you could also do this, which is a little less verbose (and what I've decided to do for my project):
/**
* #callback myCallback
* #param {Object} data An object that contains important data.
*/
/**
* #param {module:testModule~myCallback} cb a callback function
* #return {boolean} always returns true
*/
That will properly link to myCallback and document it as a member of the module.

Related

Correct way to use JSDoc with anonymous object and functions of this object

Currently using Webstorm in a project with Dojo (1.10), and ESRI API Javascript.
I have a function that accept a Widget (Object/Class), but the Webstorm show me some warnings because of JSDoc.
Code:
/**
* Init toolbar
*
* #param {Object} [options] - Toolbar options
* #param {string} [options.title=Default title] - Main title
* #param {ToolbarWidget} toolbarObj - Toolbar widget to set
*/
initToolbar: function(options, toolbarObj) {
...
toolbarObj.set('title', _title);
}
The first warning was on 'toolbarObj'. I get a message 'Unresolved variable or type'.
This was easy to resolve. Just included the following JSDoc:
/**
* A dojo widget (toolbar).
* #typedef {Object} ToolbarWidget
*/
Now, the another warning was the 'set' function of toolbarObj.
I get a warning with the following message: 'unresolved function or method set()'.
Already tried #name, #function (maybe not in the correct way)!
I known this is optional (is just a warning), but, I like to document everything in the right way.
So, how I can document the 'set' function of a anonymous object/dojo widget?!
What about
/**
* A dojo widget (toolbar).
* #typedef {Object} ToolbarWidget
* #property {function} set
*/

How do I document NodeJS native (V8) modules?

I have developed a native NodeJS module (using the NAN helpers). Now I am wondering what is the best way to document it.
The methods the module exports exist only in the C++ source code, however I wish to export Javascript documentation.
EDIT: I found another way that I think is better:
All JSDoc needs is to be able to attach the doclet to SOMETHING, so you can actually just do this (if you ignore JSHint warning about expecting an assignment or call instead of expression):
var nativeStuff = require('some/native/stuff');
/**
* My Cool Class
* #class
*/
nativeStuff.MyCoolClass;
/**
* My Cool Method
* #function
* #param {String} [name] The argument
*/
nativeStuff.MyCoolClass.prototype.CoolMethod;
/**
* Some Other Value
* #type {String}
*/
nativeStuff.someStringValue;
module.exports = nativeStuff;
This has the advantage of working with IDE's (at least WebStorm) and not requiring you to copy or proxy the object itself. Note though that you have to explicitly tell it what kind of field each entry is (with #function or #class or #type) because it can't infer it automatically otherwise.
Original Answer
There are a couple ways I know of, though I admit none seem particularly elegant.
In the small adapter file where you require() the native parts of the code and make it available as a module, you can assign each component individually and document them that way:
var nativeStuff = require('some/native/stuff');
// If your module only has one thing
/**
* My Cool Class
* #class MyCoolClass
*/
module.exports = nativeStuff;
// If it has several things
module.exports = {
/**
* My cool class
* #class
*/
MyCoolClass: nativeStuff.MyCoolClass,
/**
* My Other Cool Member
*/
OtherCoolMember: nativeStuff.OtherCoolMember
};
You could document members of the class this way too if you want to pick apart the class and re-assemble it, but it gets kinda unwieldy the deeper you go.
The other way I know of is to wrap every class method in native JS, which comes with a (almost negligible) performance hit:
var nativeStuff = require('some/native/stuff');
/**
* My Cool Class
*/
class MyCoolClass {
constructor() {
this._nativeObj = new nativeStuff.MyCoolClass();
}
/**
* Some Cool Method
* #param {String} [name] My name
*/
coolMethod(name) {
return this._nativeObj(name);
}
}
module.exports = MyCoolClass;
(Note this also works in older JS versions, but ES6 classes make stuff way easier to understand visually :)
You also can try using the #typedef directive to define things since a doclet about a typedef can be separate from the object it describes, but I don't think typedef's can document methods or classes in general, they're just for data objects.
I had to create a simple documentation generator to scan comments in source code in Javadoc-like style: https://github.com/aspectron/gendoc
Here is a part of such documentation, that looks like this:
/**
#module crypto
**/
/**
#class Hash
Hash generator
#function Hash(algorithm)
#param algorithm {String}
Constructor. Initiaize hash generator with specified algorithm, see #getHashes
Throws exception on unknown algorithm
**/
v8pp::class_<hash_generator> hash_class(bindings.isolate(), v8pp::v8_args_ctor);
hash_class
/**
#function reset([algorithm])
#param [algorithm] {String}
#return {Hash}
Reset hash generator to initial state optionaly changing generator algorithm.
Throws exception on unknown algorithm.
**/
.set("reset", &hash_generator::reset_v8)
...
Finally I opted for a not very elegant solution. I have created a separate JavaScript file which only has methods that are exported by my native API.
This file looks like this:
/** #namespace AwesomeLibrary
*
* #description API overview
*/
AwesomeLibrary = {
/**
* #param {string} param Input parameter
* #return combobulates {#link param}
*/
combobulate: function (param) {}
}
Then I am using JsDoc to generate the documentation of the project and passing this JavaScript file as an input rather than my native code. Finally I bundle the documentation with the binary distribution of my module.
This solution is not ideal as the documentation and the source code have to be maintained separately, however it has the advantage of zero overhead and a (rather) clean file. I have also disabled the source code generation in JsDoc as this would be obviously quite useless and only show the empty stubs.

JsDoc, ES6 and #param {Constructor}

I am trying to use JsDoc to document es6 classes. Can't believe that you can't pass a class as a parameter (a class type, not an instance type).
I've been trying things but can't get this simple code to work so that JsDoc doesn't throw me some warnings.
I can't get it to work unless I create a #typedef for each of my classes, then add manually all own and inherited members to it. Can't even do a mixin!
Has anyone succeeded in passing a constructor/class parameter? So that JsDoc be in the static context, not the instance context?
/**
* #class A
*/
class A {
/**
* #static
*/
static helloFromClassA(){
}
}
/**
* #class B
* #extends A
*/
class B extends A{
/**
* #static
*/
static helloFromClassB(){
}
}
/**
* Class as object
* #param {A} ClassArgument
*/
function fn1(ClassArgument){
ClassArgument.helloFromClassA(); // Unresolved function or method helloFromClassA
// Does not work because ClassArgument is interpreted as an
// instance of A, not A's constructor
}
/**
* // Class as function
* #param {Function} ClassArgument
*/
function fn2(ClassArgument){
ClassArgument.helloFromClassA(); // Unresolved function or method helloFromClassA
// Does not work because ClassArgument is interpreted as an
// empty function, not A's constructor
}
/**
* // Type definition
* #typedef {Object} AClass
* #property {Function} helloFromClassA
* #property {Function} super
*/
/**
* // Trying to mixin the AClass
* #typedef {Object} BClass
* #property {Function} helloFromClassB
* #mixes {AClass}
* #mixes {A}
*/
/**
* // Adding manually all members
* #typedef {Object} BClass2
* #property {Function} helloFromClassB
* #property {Function} helloFromClassA
*/
/**
* #param {BClass} ClassArgument
*/
function fn3(ClassArgument){
ClassArgument.helloFromClassA(); // Unresolved function or method helloFromClassA
// Does not work because the BClass typedef does not take
// into account the mixin from AClass, nor from A
ClassArgument.helloFromClassB(); // No warming
}
/**
* #param {BClass2} ClassArgument
*/
function fn4(ClassArgument){
ClassArgument.helloFromClassA(); // No Warning
ClassArgument.helloFromClassB(); // No warming
// Works because we manually defined the typedef with all own
// and inherited properties. It's a drag.
}
fn1(B);
fn2(B);
fn3(B);
fn4(B);
jsDoc issue : https://github.com/jsdoc3/jsdoc/issues/1088
I've been running into same issue with auto-completion in WebStorm multiple times. While it looks like currently there is no straight-forward way in jsdoc to say that parameter is a reference to a constructor (not to an instance), there is a suggestion from JetBrains team to implement something like #param {typeof Constructor} (where typeof is from typescript) or #param {Constructor.} that was suggested by closure compiler team. You can vote for following issue to get your main concern with WebStorm autocompletion resolved - https://youtrack.jetbrains.com/issue/WEB-17325
In Visual Studio Code, you can specify
#param {function(new:MyClass, SomeArgType, SecondArgType, etc...)}
I'm not sure what spec that syntax comes from or who else supports it, but it Works For Me.
typescript and google closure both support {typeof SomeClass} for referencing a class as a type (not a class instance). Unfortunately jsdoc doesn't support that syntax and will fail to compile it (https://github.com/jsdoc3/jsdoc/issues/1349).
Because I want to type-checking my JavaScript with typescript and also want to generate documentation I made this jsdoc plugin to transform expressions like {typeof SomeClass} into {Class<SomeClass>} so I can have both things: https://github.com/cancerberoSgx/jsdoc-typeof-plugin

JSDoc within AngularJS services

I'm creating an AngularJS service to validate form inputs and I can't for the life of me figure out how to use JSDoc3 to create reasonable documentation.
Ideally I need to export the documentation for the validator service as well as the documentation for each validator (internal objects)
After googling around a bit I was able to get it kind of working by hacking around a bit with namespaces, but I'm wondering if there's a right way to do this. A way that won't muck up somebody else's JSDoc if they include my service.
Example:
angular.module('services.utility')
.factory('validator', [function () {
var validators = {
/**
* Requires a field to have something in it.
* #param {String|Boolean} val The value to be checked.
* #return {Object}
*/
'required': function(val){
// check against validator
return {'valid': true, 'msg': 'passed!'};
},
/**
* Requires a field to be less than a number.
* #param {Number} val The value to be checked.
* #param {Number} check The value to be checked against.
* #return {Object}
*/
'lessThan': function(val){
// check against validator
return {'valid': true, 'msg': 'passed!'};
}
};
return {
/**
* This is the main validation routine.
* #param {Object} vObjs An object to be processed.
* #return {Boolean}
*/
'validate': function(thingsToValidate){
// run some validations from the validators
// and return a bool.
}
};
}]);
In a perfect world, modifications to the above would let me generate a nice, non-global, JSDoc hierarchy where a user could read about how to use the validator as a whole, or dive in and look what needed to be passed in for each type of validation.
Thanks so much for any help you can give!
The way my team works is that we actually only document the actual factory function as if the user were going to read it. You've actually skipped over that guy. Either way, you can treat that as the entry point for your documentation and combine it with your "method" documentation for the full picture. You could make use of the #namespace documentation in combination with this.
/** Here is how you use my factory. #param #return */
my.validator.factory = function() { return { validate: function(){} }; }
/** Here are some validators. #enum {Function(*):ValidationResult} **/
my.validator.Validators = {}
module.factory('validator', my.validator.factory);
Depending on what you really want, you may prefer to use a prototype. That's where documentation can really shine:
/** Here is how you use my factory. #param #return #constructor */
my.Validator = function() {}
/** My validation function. #param #return */
my.Validator.prototype.validate = function() {}
/** Here are some validators. #enum {Function(*):ValidationResult} **/
my.Validator.Validators = {}
module.service('validator', my.Validator);
Using the prototype with your documentation really sticks it all together for me. It's like documenting your validator as one class entity, which makes the most sense to me.

How to include an already documented method in jsdoc-toolkit?

I have a JavaScript singleton object created with closure method:
/**
* This is the singleton.
*
* #namespace window.Something.Singleton
*/
window.Something.Singleton = (function() {
/**
* Foo method.
*
* #return {String} this method always returns with <code>bar</code>
*/
function _foo() { return "bar"; }
/**
* #lends window.Something.Singleton#
*/
return {
/**
* #borrows window.Something-_foo
* #function
*/
foo: _foo
};
}());
But the jsdoc-toolkit does not generate the inherited documentation from _foo method to the foo method what I would like to have.
If I write #see instead of #borrows it works (inserts a link to the correct method), but I don't want to copy&paste the documentation for the foo method to have a public documentation as well.
I did some tests, and I have good news and bad news :). The good news is that it looks like you can get this to work by putting the #borrows tag in the Singleton doc comment:
/**
* This is the singleton.
*
* #namespace Something.Singleton
* #borrows Something.Singleton-_foo as foo
*/
Something.Singleton = (function() {
// etc
})());
But this has several ramifications, good and bad:
The foo function is marked static. This is probably a good thing, as it seems to be accurate as I understand your code.
With the code as it is currently shown (i.e. no more methods on the singleton, etc), you can dispense with the #lends tag entirely, unless you want to include it for clarity. If all methods are listed as #borrows on the top singleton namespace, then you don't need to further document them in the returned object. Again, this is probably a good thing.
The bad news is that I couldn't get this to work unless the borrowed method was explicitly marked #public - which makes it show up, redundantly, in the documentation. I think this is unavoidable - if jsdoc-toolkit thinks the method is private, it won't create documentation, so you can't refer to it (I get WARNING: Can't borrow undocumented Something.Singleton-_foo.). If the method is public, it gets displayed in the documentation.
So this works:
/**
* This is the singleton.
*
* #namespace Something.Singleton
* #borrows Something.Singleton-_foo as foo
*/
Something.Singleton = (function() {
/**
* #public
* Foo method.
*
* #return {String} this method always returns with <code>bar</code>
*/
function _foo() { return "bar"; }
return {
foo: _foo
};
}());
...in that it copies the documentation for _foo to foo, but it will display _foo in the documentation page as well:
Method Summary
<inner> _foo()
<static> Something.Singleton.foo()
Probably the best workaround is simply to forget #borrows entirely and explicitly name _foo as Something.Singleton.foo in the doc comment, marking it as a public function (you could dispense with #public if you didn't name your inner function with an underscore, but this tells jsdoc-toolkit to treat it as private unless told otherwise):
/**
* This is the singleton.
*
* #namespace Something.Singleton
*/
Something.Singleton = (function() {
/**
* #name Something.Singleton#foo
* #public
* #function
* Foo method.
*
* #return {String} this method always returns with <code>bar</code>
*/
function _foo() { return "bar"; }
return {
foo: _foo
};
}());
This will produce the code documentation you're looking for, and puts the comment next to the actual code it relates to. It doesn't fully satisfy one's need to have the computer do all the work - you have to be very explicit in the comment - but I think it's just as clear, if not more so, than what you had originally, and I don't think it's much more maintenance (even in your original example, you'd have to change all your doc comments if you renamed Something.Singleton).
http://code.google.com/p/jsdoc-toolkit/wiki/TagBorrows
#borrows otherMemberName as thisMemberName
otherMemberName - Required: the namepath to the other member.
thisMemberName - Required: the new name that the member is being assigned to in this class.
/** #constructor */
function Remote() {
}
/** Connect to a remote address. */
Remote.prototype.transfer = function(address, data) {
}
/**
* #constructor
* #borrows Remote#transfer as this.send
*/
function SpecialWriter() {
this.send = Remote.prototype.transfer;
}
Any documentation for Remote#transfer will also appear as documentation for SpecialWriter#send.

Categories