JavaScript coding standards
Encapsulation
Inheritance
Namespaces/packages
Naming convention for packages is lowercase.
Create base class:
var twiki = {}
Create subclass:
twiki.String = {
// functions here
}
JSUnitContrib
To separate markup and logic and to provide graceful degradation I have been using
BehaviourContrib.
For example, if we have a 'normal' link to TWiki Web hometopic:
TWiki Web Home, we can use javascript to make it open a popup window. When javascript is not available the link behaviour defaults to opening the page in the current window.
<span class="link%TWIKIWEB%%HOMETOPIC%">[[%TWIKIWEB%.%HOMETOPIC%][TWiki Web Home]]</span>
<script type="text/javascript">
// <![CDATA[
var myrules = {
'.link%TWIKIWEB%%HOMETOPIC% a' : function(el){
el.onclick = function() {
// open in a popup with no other attributes than template 'viewplain'
launchTheWindow(this.href,null,null,null,"viewplain");
return false;
}
}
};
Behaviour.register(myrules);
// ]]>
</script>
The class name link%TWIKIWEB%%HOMETOPIC% will get expanded to linkTWiki04x03WebHome
See
demo page for this code.
JavaScript files can grow large, especially when documentation is added. Of course we wouldn't want to do away with documentation just because of the filesize.
A solution is to compress the files. The tool I've been using is
Dojo's ShrinkSafe. The results are quite impressive.
Note that when using Dojo, private members should be placed at the top of the class, followed by priviliged members.
Naming convention is to insert
.compressed in the name, for example:
twisty.js for the original file and
twisty.compressed.js for the compressed file.
Dojo has a
list of Javascript Programming Conventions.
--
Contributors: ArthurClemens - 29 Oct 2006