JavaScript Conventions
This page is outdated and no longer receives updates!
This page contains recommended conventions for JavaScript Development, both in the browser and on the server via Node.
Namespacing
It's a good idea to namespace any functions, objects, or other Javascript variables you include in your code in order to avoid name collisions with other parts of OpenMRS, or any 3rd party javascript libraries we include. If you're working on a module you can use openmrs.module_id for your namespace. A simple way to achieve this, using the reporting module as an example, is with the following idiom that can be included at the top of the javascript for any page.
var openmrs = openmrs || {};
openmrs.reporting = openmrs.reporting || {};
// Now use the namespace for functions, etc
openmrs.reporting.triggerReport = function(args) { };
Â
Syntax
Follow felixge's Node Style Guide. In JavaScript projects such as Modulus and OpenMRS ID, these standards help improve readability and collaboration on code.
Use JSHint to detect potential errors and structural problems as you code. There's also a .jshintrc file that enforces the style guide in your code — install it simply by placing it in your source code's directory or a parent directory.
Documentation
Any non-trivial JavaScript code should be documented. We primarily use jsdoc in our projects, except when writing AngularJS apps, where JSDoc is superceded by ngdoc. The jsdoc/ngdoc syntax is very similar to JavaDoc. In some editors, like Sublime Text, packages like DocBlockr are available that assist in writing method-level documentation.
Testing
Like any other mature codebase, non-trivial JavaScript code must be tested. We recommend unit testing code with Jasmine, and running tests via Karma (for AngularJS apps, see their unit testing guide). Additionally, Mocha has been used in some areas of OpenMRS ID and had similar success.
References
Even though it's a few years old, Crockford's Javascript: The Good Parts is still likely required reading. It's also really short and it a quick read.