Tutorial: Code Completion

Some JavaScript IDEs/editors have the ability to suggest available properties and methods in JavaScript while typing. Some can also display documentation associated with the suggestions. These editors rely on having access to the JavaScript source in order to create a list of suggestions and documentation. WAT, however, uses built-in function and class definitions that are only accessible from devices (or simulators) running WAT software. To overcome this, a 'fake' definition of the WAT objects can be included in a web project. This file typically does not need to be referenced or included by the files that are actually deployed, it is usually enough to just include in in the project, as its purpose is only to provide hints to the editor.

An example of such a file is fakewat.js. Add this file to a web project to assist the IDE with code completion. Different IDEs/editors have different implementation of code completion, so only a portion, or none of the WAT objects may have code completion depending on which IDE is used.

Because JavsScript variables have no type when they are defined, it is often difficult for an IDE to determine what type a variable may be at any given time and thus provide a good set of suggestions for code completion. It often helps to give the IDE a hint as to what type (or type) the variable will be used as with a comment:

/**
 * @type {ui.UI}
 */
 var ui = $wat.load('ui')[0];

Some IDEs behave better when the '{' and '}' are not used in the @type declaration. Experiment to see what works best. The fakewat.js file uses a combination of both methods in an attempt to target a wider range of IDEs.

Some IDEs only offer completion suggestions when editing JavaScript that is in a separate *.js file, rather than embedded in the HTML. This is often a good practice anyway. Most of the samples, however, do have JavaScript embedded in the HTML, but this is only to reduce the number of files required to try the sample.

Some examples of IDEs that may support code completion:

  • Aptana (or other Eclipse-based IDEs)
  • WebStorm

While fakewat.js does not need to be included in the deployed project, it can still safely be included because it checks for WAT prior to setting up the fake implementation. This may prove useful if the project needs to run in a non-WAT browser for some reason (such as if an external tool is used for testing). However, it would likely need some modification in order to return different results from method calls.