See www.zabbix.com for the official Zabbix site.

JavaScript coding guidelines

From Zabbix.org
Jump to: navigation, search

General

  • Using global variables should be avoided as much as possible.

Naming conventions

  • All names should be written in English.
  • Function (except constructors) names must be in lower camel case.

Example:

// correct
function create() {
    // some logic here
}

function getName() {
    // some logic here
}

// wrong
function Create() {
    // some logic here
}

function get_name() {
    // some logic here
}
  • Variables should be written in lowercase characters separated by underscores.

Example:

// correct
var hostid = 12345,
	item_applications = [];

// wrong
var Hostid = 12345,
	itemApplications = [];
  • "$" character as first letter in variable name should be used for and only for variables, containing jQuery object.

Example:

// correct
var $widget_header = $('.widget_header', $widget),
	host_count = 5;

// wrong
var widget = $('.widget_container'),
	$hosts = [$('#host1'), $('#host2')];
  • Constructor function names must be in upper camel case.

Example:

// correct
var CTimeLine = Class.create({});

// wrong
var cTimeLine = Class.create({}),
	ctimeline = Class.create({}),
	c_time_line = Class.create({});
  • Words in HTML data attribute names must be separated by dashes; when accessing them via the jQuery data() method they must be written in camel case.

Example:

<!-- correct -->
<img data-height="50">
<span data-toggle-class="blink">
// correct
var height = $obj.data('height'),
	toggle_class = $obj.data('toggleClass');

Variables

Variable declaration

  • Each variable must be declared on a separate line. Multiple variables are separated by comma.

Example:

// correct
var itemids = [],
    item_applications = [];

// wrong
var itemids = [];
var item_applications = [];

// wrong
var itemids = hostids = [];

// wrong
var left = null, top = null, right = null, bottom = null;

// wrong
var itemIds = [],
    itemApplications = [];

Objects

  • Creating object entities must be without quotes.

Example:

var person = {firstname: 'Mario', lastname: 'Smith'};

person.firstname = 'Mr.';

Assignments

  • Multiple left-hand assignments in one line are discouraged and shouldn't be used.
// correct
curr_lbl.style.background = background;
curr_lbl.style.color = background;

// wrong
curr_lbl.style.background = curr_lbl.style.color = background;
  • A complex statement assigned to a variable must be wrapped in parenthesis.
// correct
var disable = ($('#mass_border_type').val() === '-1' && $('#chkboxBorderType').is(":checked"));

// wrong
var disable = $('#mass_border_type').val() === '-1' && $('#chkboxBorderType').is(":checked");
  • The opening brace is written on the same line as the conditional statement.

Conditional statements

  • The opening brace is written on the same line as the conditional statement.
  • The closing brace is always written on its own line.

Example:

// correct
if (list.length > 100) {
    // some logic here
}

// wrong
if (list.length > 100)
{
    // some logic here
}

If/Else/Else if

  • "if" statements always use curly braces {}.

Example:

// correct
if (list.length > 100) {
    // some logic here
}

// correct
if (list.length > 100) {
    // some logic here
}
else {
    // some logic here
}

// correct
if (list.length > 100) {
    // some logic here
}
else if (list.length == 1) {
    // some logic here
}
else {
    // some logic here
}

// wrong
if (list.length > 100) // some logic here

if (list.length > 100) {
    // some logic here
} else {
    // some logic here
}
  • Use "else" or "else if" when possible, avoiding separate "if" statements.

Example:

// correct
if (a == b) {
    d = e;
}
else if (a == c) {
    d = f;
}
else {
    d = g;
}

// wrong
if (a == b) {
    d = e;
}
if (a == c) {
    d = f;
}
if (a != b && a != c)
    d = g;
}

Switch

  • If we fall through, comment should be present, confirming that it's intentional.

Example:

switch (condition) {
    case 1:
        // some logic here
        // falls through
    case 2:
        // some logic here
        break;
 
    case 3:
        // some logic here
        break;
 
    default:
        // some logic here
        break;
}

Try/Catch

Example:

try {
    // some logic here
}
catch (exception if condition) {
    // some logic here
}
finally {
    // some logic here
}

Loops

For

Example:

for (var i = 0; i < list.length; i++) {
    // some logic here
}

While

Example:

while (list.length > 0) {
    // some logic here
}

Do/While

Example:

do {
    // some logic here
} while (list.length > 0);

Formatting

  • Indentation should consist of tabs.
  • Maximum line length is 120 characters.

Strings

Example:

$('#expressions_' + index + '_expression').val()

Blank spaces

  • One blank space should appear after commas in argument lists:
// correct
function updateUserProfile(idx, value_int, idx2) {
    // ...
}

// wrong
function updateUserProfile(idx,value_int,idx2) {
    // ...
}
  • All binary operators should be separated from their operands by spaces. Blank spaces should never separate unary operators such as unary minus, increment ("++"), and decrement ("--") from their operands.
  • A keyword followed by a parenthesis should be separated by a space:
// correct
if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
    n = (n > 0 || -1) * Math.floor(Math.abs(n));
}

// wrong
if(n!==0&&n!==(1/0)&&n!==-(1/0)){
    n=(n>0||-1)*Math.floor(Math.abs(n));
}
  • A keyword after colon should be separated by a space.
// correct
init: function(time) {
    this.delay = time;
    this.delayLeft = this.delay;
    this.start();
}

// wrong
init:function(time) {
    this.delay = time;
    this.delayLeft = this.delay;
    this.start();
}

Blank lines

  • A blank line should be added after variable declaration, before and after statements and before return.
// correct
var footerButton = jQuery(e.target),
    form = footerButton.closest('form'),
    confirmText = footerButton.attr('confirm');

if (confirmText && !confirm(confirmText)) {
    Event.stop(e);

    return false;
}

// wrong
var footerButton = jQuery(e.target),
    form = footerButton.closest('form'),
    confirmText = footerButton.attr('confirm');
if (confirmText && !confirm(confirmText)) {
        Event.stop(e);
        return false;
}

Comments

  • License comments should not be minified ( comment with /*! ).
  • Double slashes are used in simple comments.

Example:

// simple comment
  • Full sentence in a comment starts with a capital letter and ends with a dot.

Example:

// This is a full sentence comment.
  • Block comments can be used with the first letter being capital.

Example:

/*
 * New block comment.
 */
  • Full words should be used in comments instead of shortened versions - for example, "parameter" instead of "param".
  • Multiline comments should use "block comment" syntax and should not exceed maximum line length.
  • If code is self-explanatory, comments should not be used.

JSDoc

  • All functions, methods and properties should have a JSDoc comment with a brief description of it's purpose and interface. Tag descriptions should be aligned using spaces and tags belonging to one group should be separated by a single line to improve readability. If function doesn't return value @return is not needed. For more than two return types it's better to combine types using the pipe char instead of mixed.
  • Parameter types are encapsulated with {} and start with lowercase letter.
  • Each parameter should have a description.

Example:

/**
 * Performs a cool magic trick.
 * 
 * @param {object}   fairy_dust        The FairyDust object to use in the trick.
 * @param {array}    magic_stones      An array of magic stones.
 * @param {number}   stones_limit      Limit of magic stones.
 * @param {string}   stones_owner      The name of the stones owner.
 * @param {bool}     is_destructable   Are the magic stones desctructable.
 *
 * @return {object}
 */
function performMagic(fairy_dust, magic_stones, stones_limit, stones_owner, is_destructable) {
    // some magic here
}

Comparison

  • The "Equal" or "Not equal" operators must be used to compare numeric values to zero.

Example:

// good
if (itemid != 0) {}

// bad
if (itemid) {}
  • To check for undefined use "typeof variable === 'undefined'".

Attributes

  • To get value of data-* attribute as string use "attr" method instead of "data".

Example:

// good
var id = obj.attr('data-id');

// bad
var id = obj.data('id');