1

When using arrow functions (e.g. on document elements event handlers), they are labeled after the event handler name in the VS Code outline. enter image description here

Since I have quite a lot of them, the outline is little helpful quickly navigating to a certain one.

How to annotate a name for such arrow functions?

Using JSDoc works fine for params descriptions, but I haven't figurend out how to add a name. I'd expect the @function tag to do so, but it doesn't. :(

/**
 * @function onMyButtonClick
 * @param {Event} event Triggering event.
 */
document.getElementById("my-button").onclick = (event) => { /* my function */ };

Using a function assignment instead of an arrow function looks good in the outline, but (unneccessary to mention) it is not the same as an arrow function (e.g. the this context get lost). So this is NOT a solution.

/**
 * @param {Event} event Triggering event.
 */
document.getElementById("my-button").onclick = function onMyButtonClick (event) { /* my function */ };
  • Have you tried using `@name`? https://jsdoc.app/tags-name.html – Konrad Oct 25 '22 at 17:24
  • Does [this](https://stackoverflow.com/questions/27977525/how-do-i-write-a-named-arrow-function-in-es2015) help you ? – bbbbbbbboat Oct 25 '22 at 17:45
  • @KonradLinkowski: Yes, I've triey `@name` and `@alias`, too. Neither did work. – Suppenhuhn79 Oct 25 '22 at 17:58
  • What about declaring arrow function in a different line? – Konrad Oct 25 '22 at 18:02
  • 1
    @bbbbbbbboat: Thanks, that gave me a better understanding of arrow functions as an assignment to a property - `onclick` in my example, so it's logical that the name of the function is "onclick" since this is where it's assigned to. JS knows of chained assignments, so I can use `let onMyButtonClick = document.getElementById("my-button").onclick = (event) => { /* my function */ };` which shows in the outline a variable `onMyButtonClick` with a nested function `onclick`. Not that nice as I whished for, but probably the closest to get to. – Suppenhuhn79 Oct 25 '22 at 18:04

2 Answers2

1

The accepted solution doesn't work in all cases, like some arrow function cases.

The alternative is to inline a @type.

For example:

const result = obj.someMethodWithCallback((/** @type {Event} */ event) => {
  //...
});
Jason Polites
  • 5,571
  • 3
  • 25
  • 24
0

Well, finally figured it out. It has to be a chained assignment:

/**
 * @param {Event} event Triggering event.
 */
document.getElementById("my-button").onclick = onMyButtonClick = (event) => { /* my function */ };

That way, the outline shows just the function name ("onMyButtonClick") as a function - just as desired