Typedefs

Typedefs are a convention to document object patterns. They are not part of JavaScript and cannot be used in real code. They are used as a documentation pattern to make it easy for developers to know what parameters are expected to a function without the need to read the code of the function.

For example, if we want to create an instance of Mapspace.control.Button class and we go to the documentation, we can see it has an optional argument Mapspace.control.ButtonOptions. As JavaScript do not prevents from passing any number of arguments of any type when calling a function, developers must take care of passing the correct values checking the definition of the parameters. In this case, the definition of Mapspace.control.ButtonOptions has these possible values:

  • target: the HTML element to locate the control
  • controls: an optional array of subcontrols
  • classNames: an optional string with classnames to be added to the HTML element
  • globalizationKey: an optional key to use for searching for language translations
  • fadeOut: an optional parameter to control how the button is faded in/out
  • handleResizing: for handling resizing of the control on resize events
  • iconClassNames: a way to set icons using classnames
  • iconSVG: a recommended way to set icons using SVG
  • iconStyle: how to show the icon
  • label: the label of the button
  • tooltip: the Mapspace.control.Tooltip object with the tooltip
  • size: size for the control
  • handler: an optional function that a button can have and will be called when clicked

Typedefs are not JavaScript code as they are only declarations; do not produce any JS executable code. The purpose is just to serve as a documentation mark that will produce a section in the API doc so developers can use it. In this case we can see that the only one parameter that the Button constructor expects as argument must be an object with several properties. All of them can be set to undefined, so default values will be provided for missing ones. You must take care of properties that cannot be undefined in typedefs because that means that a valid value is expected in that property or probably an error will be thrown.

For example, this is a valid initialization of a Button:

// Initialization with no parameters at all (allowed in typedef)
var myControl = new Mapspace.control.Button();

// Initialization with parameters
var myControl2 = new Mapspace.control.Button({
    target: 'container',
    classNames: 'btn-light my-button my-controls',
    label: 'Execute',
    handler: function() {
        console.log('We are executing a process. But not today. Tomorrow!');
    }
});

As you can see we do not need to set all the properties defined in the typedef if they allow an undefined value. globalizationKey, iconClassNames, iconSVG, etc. will be set with their default values, and target, classNames, label and handler with the values provided.