Here is how we are using Javascript when coding for Beansight (this article is a draft)
It also details how we deal with our web framework: Play! Framework.
Plugins
Available globally :
- jQuery
- jQuery UI
- jQuery validate
If a plugin needs to be used on very few pages, use #{set ‘moreScripts’ } of the Play! Framework
Code Convention
Read and try to use every convention described one this page.
Including:
- Javascript code should not be in the HTML body. Put javascript code in beansight.js. If your code should be executed after the page has been created, put it in $(document).ready(function() { of beansight.js
Specific to the Play! Framework
Actions URL
URLs to Play! actions are generated by Play!, thus they cannot be in beansight.js because this file is not generated.
A way to generate Play! action URLs in the .js file is by doing this :
in main.html :
<!-- define here the actions -->
<script type="text/javascript">
var agreeAction = #{jsAction @Application.agree(':insightId') /};
</script>
in beansight.js :
agreeAction({'insightId': insightId})
generates the action URL.
i18n
Messages are generated by Play! depending on the current language, but beansight.js cannot be generated.
messages must be written in /public/javascripts/i18n/XX.js
add a line in these files:
yourstringid : “My String”,
in Javascript code, to use a string, do :
i18n.yourstringid
How does it works ?
In main.html, this line loads the right message file :
<!-- load the right i18n file -->
<script src="/public/javascripts/i18n/&{'i18n'}.js" type="text/javascript" charset="utf-8"></script>
This mechanism should be improved: defining a default language, fallback to default if the string is not found.
Tools
FireBug
- use breakpoints
- watch the console for errors
- watch the AJAX requests
JSLint
JSLint, a Javascript validator can be helpfull (not used for the moment)
Links
Google’s guidelines : http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml
Understand closures : https://developer.mozilla.org/en/JavaScript/Guide/Closures