Jump to: navigation, search

Difference between revisions of "Horizon/Javascript"

(Required:)
(Required:)
Line 121: Line 121:
 
* Since Django already uses '{{ }}', use '{$ $}' or '{% verbatim %}' instead.
 
* Since Django already uses '{{ }}', use '{$ $}' or '{% verbatim %}' instead.
  
* For localization of text in JavaScript files use 'gettext("translatable text")'.  Only 'gettext' is recognized by our tools and will be included in the po file after running './run_tests --makemessages'.
+
* For localization of text in JavaScript files use 'gettext("translatable text")'.  Only 'gettext' is recognized by our tools and will be included in the '.po' file after running './run_tests --makemessages'.
  
 
* For localization of AngularJS templates in Horizon, there are a couple of ways to do it.
 
* For localization of AngularJS templates in Horizon, there are a couple of ways to do it.

Revision as of 18:10, 16 January 2015

Code Style

As a project, Horizon adheres to code quality standards.

JavaScript

The following standards are divided into required and recommended sections. Our main goal in establishing these best practices is to have code that is reliable, readable, and maintainable.


Required:


Before committing your code, please review the following checklists: 'Reliable' and 'Readable and Maintainable'. Though we all have our preferences, these are the most commonly accepted guidelines.

Reliable

  • The code has to work on the stable and latest versions of Firefox, Chrome, Safari, and Opera web browsers, and on Microsoft Internet Explorer 9 and later.
  • If you turned compression off during development via 'COMPRESS_ENABLED = False' in local_settings.py, re-enable compression and test your code before submitting.
  • Use '===' as opposed to '==' for equality checks. The '==' will do a type cast before comparing, which can lead to unwanted results. Note: If typecasting is desired, explicit casting is preferred to keep the meaning of your code clear.
  • Keep document reflows to a minimum. DOM manipulation is expensive, and can become a performance issue. If you are accessing the DOM, make sure that you are doing it in the most optimized way. One example is to build up a document fragment and then append the fragment to the DOM in one pass instead of doing multiple smaller DOM updates.
  • Use “strict”, enclosing each JavaScript file inside a self-executing function. The self-executing function keeps the strict scoped to the file, so its variables and methods are not exposed to other JavaScript files in the product. Note: Using strict will throw exceptions for common coding errors, like accessing global vars, that normally are not flagged.
  Example: 
    (function(){
       'use strict'; 
        // code...
    }) ();
  • Use for each when looping whenever possible. AngularJS, and jQuery both provide for each loops that provide both iteration and scope.
  AngularJS:
    angular.forEach(objectToIterateOver, function(value, key) {
        // loop logic
    });

  jQuery:
    $.each(objectToIterateOver, function( key, value ) {
       // loop logic
    });
  
  • Do not put variables or functions in the global namespace. There are several reasons why globals are bad, one being that all JavaScript included in an application runs in the same scope. The issue with that is if another script has the same method or variable names they overwrite each other.
  • Always put 'var' in front of your variables. Not putting var in front of a variable puts that variable into the global space, see above.
  • Do not use 'eval( )'. The eval (expression) evaluates the expression passed to it. This can open up your code to security vulnerabilities and other issues.
  • Do not use 'with object {code}'. The 'with' statement is used to access properties of an object. The issue with 'with' is that its execution is not consistent, so by reading the statement in the code it is not always clear how it is being used.


Readable & Maintainable

  • Give meaningful names to methods and variables
  • Avoid excessive nesting.
  • Avoid HTML and CSS in JS code. HTML and CSS belong in templates and stylesheets respectively. For example:
  * In our HTML file, we should focus on layout.

      1. Reduce the small/random '<script>' and '<style>' elements in HTML.
      2. Avoid in-lining styles into element in HTML. Use attributes and classes
         instead

  * In our JS files, we should focus on logic rather than attempting to manipulate
    style elements. 

      1. Avoid statements such as 'element.css({property1,property2...})' they belong in a CSS
         class.
      2. Avoid statements such as '$("<div><span>abc</span></div>")' they belong
         in a HTML template file. Use 'show' | 'hide' | 'clone' elements if dynamic content is required.
      3. Avoid using classes for detection purposes only, instead, defer to
         attributes.

          For example to find a div: 
            <div class="something"></div> 
             $(".something").html("Don't find me this way!");
          
          Is better found like: 
            <div data-something></div> 
             $("div[data-something]").html("You found me correctly!");
  • Avoid commented-out code.
  • Avoid dead code.


Recommended:


Readable & Maintainable

  • Put a comment at the top of every file explaining what the purpose of this file is when the naming is not obvious. This guideline also applies to methods and variables.
  • Source-code formatting – (or “beautification”) is recommended but should be used with caution. Keep in mind that if you reformat an entire file that was not previously formatted the same way, it will mess up the diff during the code review. It is best to use a formatter when you are working on a new file by yourself, or with others who are using the same formatter. You can also choose to format a selected portion of a file only. Instructions for setting up JSHint for Eclipse, Sublime Text, Notepad++ and WebStorm/PyCharm are provided.
  • Use 2 space for code Indentation.
  • Use '{ }' for 'if', 'for', 'while' statements, and don't combine them on one line.
// Do this          //Not this          // Not this
if(x) {             if(x)               if(x) y =x;
   y=x;                y=x;                          
}
  • Use CamelCase. "HelloWorld" for classes or object prototype functions, and "helloWorld" for other uses (function declarations etc.)

AngularJS

Required:


  • Organization: Define your angular app under the root angular folder (such as 'horizon/static/horizon/js/angular/hz.table.js'). If your application is small enough you can choose to lump your Controllers, Directives, Filters, etc.. all in the one file. But if you find your file is growing too large and readability is becoming an issue, consider moving functionality into their own files under sub folders as described in the Recommended section.
  • Separate presentation and business logic. Controllers are for business logic, and directives for presentation.
  1. Controllers and Services should not contain DOM references. Directives should.
  2. Services are singletons and contain logic independent of view
  • Scope is not the model (model is your JavaScript Objects). The scope references the model. Forms must operate on properties objects on the scope, not on properties of the $scope directly (that is, ng-model must operate on dotted names). This holds for other directives modifying model data as well.
  1. Read-only in templates,
  2. Write-only in controllers
  • Since Django already uses '{{ }}', use '{$ $}' or '{% verbatim %}' instead.
  • For localization of text in JavaScript files use 'gettext("translatable text")'. Only 'gettext' is recognized by our tools and will be included in the '.po' file after running './run_tests --makemessages'.
  • For localization of AngularJS templates in Horizon, there are a couple of ways to do it.
  1. Using 'gettext' or 'ngettext' function that is passed from server to client. If you're only translating a few things, this methodology is ok to use.
  2. Use an angular directive that will fetch a django template instead of a static HTML file. The advantage here is that you can now use '{% trans %}' and anything else Django has to offer. You can also cache the page according to the locale if you know that the content is static.

Recommended:


  • Use these directories: filters, directives, controllers, and templates. Note: When you use the directory name, the file name does not have to include words like "directive" or "filter".
  • Put "Ctrl" on the end of a controller file name
  • Don't use variables like "app" that are at the highest level in the file, when Angular gives an alternative. For example use function chaining:
 angular.module('_module').controller('_controller', function($scope) {
    // controller code
 }).service('my_service', function($scope) {
   // service code
 });

JSHint

JSHint is a great tool to be used during your code editing to improve JavaScript quality by checking your code against a configurable list of checks. Therefore, JavaScript developers should configure their editors to use JSHint to warn them of any such errors so they can be addressed. Since JSHint has a ton of configuration options to choose from, links are provided below to the options Horizon wants enforced along with the instructions for setting up JSHint for Eclipse, Sublime Text, Notepad++ and WebStorm/PyCharm

JSHint configuration file:

.jshintrc

Instructions for setting up JSHint:

JSHint setup instructions

Note: JSHint is part of the automated unit tests performed by Jenkins. The automated test uses the default configurations, which are less strict than the configurations we are recommending to run in your local development environment.