0

I have an object that defines a set of actions like so:

var actions = {
    close: "action_close",
    renderPreview: "action_renderpreview",
    switchToMobile: "action_switchmobile",
    switchToTablet: "action_switchtablet",
    openConfiguration: "action_configuration",
    save: "action_save"
};

Then I have a method that I use to bind these actions to a function like so:

/**
 * Add an event handler to a toolbar action
 * @param {actions.<prop>} action - The action to bind
 * @param {string} fnCallback - The function to invoke when the action is executed
 */
function onAction(action, fnCallback) {
    this.actionHandlers[action] = fnCallback;
}

I want to use JSDoc to document that the action parameter of the onAction function should be the value of a property of the actions object. Obviously {actions.<prop>} is not the right way to do it but I was wondering if there is an easy way to achieve this.

I could document the action param as {string}, but then any random string can be passed to the onAction function, which I am trying to avoid using proper JSDoc documentation.

It might be a really straightforward solution or not possible at all / unnecessary. Either way, I can't figure it out! Thank you!

Niekert
  • 917
  • 1
  • 8
  • 20

1 Answers1

1

You are looking at it the wrong way. When you are declaring actions, declare a specific type for the property:

/**
 * @typedef {string} MyAction
 * @typedef {object} Actions
 * @property {MyAction} prop
 */

then you can use directly that type

/**
 * ...
 * @param {MyAction} action - The action to bind
 */

However, that will still allow any string. To limit the string values to a specific set, you will need jsdoc enum.

/**
 * Actions.
 * @readonly
 * @enum {string}
 */
var actions = {
   close: "action_close",
   ...
};
Sulthan
  • 128,090
  • 22
  • 218
  • 270
  • This seems to still allow any string to passed to the function. Could you elaborate a bit further perhaps? Mondays... – Niekert Nov 23 '15 at 11:48
  • @Niekert Well, that's correct. If you can assign any `string` to `prop`, then you can pass any string to `action`. Maybe you want to use an enum instead? (http://stackoverflow.com/questions/19093935/how-to-document-a-string-type-in-jsdoc-with-limited-possible-values) – Sulthan Nov 23 '15 at 12:16
  • Enum is exactly what I was looking for. Can't believe I didn't think of looking for `jsdoc enum`. Thanks for the help! I can mark your answer as accepted if you include the Enum suggestion in the answer :) – Niekert Nov 23 '15 at 13:36
  • 1
    @Niekert I overlooked the beginning of your question where you list the values otherwise I would have advised about enum sooner. – Sulthan Nov 23 '15 at 14:01
  • No worries, I didn't word my question perfectly either. Marked as accepted. Thanks again! – Niekert Nov 23 '15 at 14:42