Behavior & JavaScript Styleguide
This is a guide I use for developing my apps. I encourage you to setup one that works for your own team.
Coding Style
I write a lot of JavaScript. Here are my guidelines:
- Use hard-tabs (so you can choose whether to indent 2 or 4 spaces).
- Camel-case variables (
var myVariable = 1;
). - Constants should be all uppercase with underscores between (
var MY_CONSTANT = 1;
). -
Preface variable names with 1-2 character types:
- arrays –
var aMyVariable = [];
- boolean –
var bMyVariable = true;
- elements –
var elMyVariable = Y.one('myElement') || $('myElement');
- floats –
var fMyVariable = 1.0;
- functions –
var fnMyVariable = function() {};
- integers –
var iMyVariable = 1;
- objects –
var oMyVariable = {};
- strings –
var sMyVariable = '1';
- arrays –
- Use a space around operators, but no spaces between parenthesis and the variables they wrap.
- Always use
{
and}
brackets, and semicolons;
, even when not required. - Use the Django management command
combinestatic
to combine JavaScript files, as much as possible. - Use
//
brackets for one to two line comments, and/* */
for longer comments. - Use single quotes
''
, instead of double quotes""
for strings. Double quotes are reserved for markup. - Use only one
var
per execution context (compressibility). - Avoid attaching anything to the global namespace, use
YUI.namespace
or$MSJS
. - Newline before and after all block statements (comments are okay).
- If
this
keyword is used three or more times in a function, replace it with a variablethat
(compressibility).
// quick comment function fnMyFunction(iArg1, fArg2) { var iTestInt = 1, fTestFloat = 1.0; if (iTestInt) { iTestInt += iArg1; } return iTestInt * (fTestFloat + fArg2); } var fTestFloat = fnMyFunction(2, 2.2);
Selectors
Try to prefix all javascript-based selectors with js-
.
This is taken from slightly obtrusive javascript.
The idea is that you should be able to tell a presentational class from a functional class.