skip to Main Content

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 */ };

2

Answers


  1. Chosen as BEST ANSWER

    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 😊


  2. 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) => {
      //...
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search