JQuery Coding Standards
Follow Drupal’s JavaScript coding standardsOn this page:
Wrap $
If you want to use jQuery’s $ variable, you have to wrap your code like this:
(function($) {
// code using $ variable
})(jQuery);
The $ global variable is not used by JQueryPlugin, to avoid conflicts
with other javascript libraries that may be loaded. jQuery examples that
you find on the web will work as written, just as long as you wrap
them as described here.
Shorthands
Use the jQuery shorthand$ where possible:
$(function() { ... });
instead of
$(document).ready(function() { ... });
Global variables
If you want to use global variables within the scope of your code, wrap your code like this:
(function() {
var foo = 'bar'; // yay, it's almost like I'm global
})();
If you want to use global variables in the global scope, put the variable in the foswiki namespace:
foswiki.foo = 'bar';Mind the predefined global variables. See next section.
Propagating perl settings to javascript
The standard foswiki library initializes the globalfoswiki object with
a subset of preference settings from foswiki, SCRIPTURLPATH, SCRIPTSUFFIX, and PUBURLPATH. These are sufficient to call scripts on the server and build attachment URLs. They are accessed using the foswiki.getPreference method:
var pubUrlPath = foswiki.getPreference('PUBURLPATH');
In addition, the JQuery foswiki plugin adds the macros specified by the
global EXPORTEDPREFERENCES preference (currently PUBURL, PUBURLPATH, SCRIPTSUFFIX, SCRIPTURL, SCRIPTURLPATH, SERVERTIME, SKIN, SYSTEMWEB, TOPIC, USERNAME, USERSWEB, WEB, WIKINAME, WIKIUSERNAME, NAMEFILTER).
Avoid Internet Explorer errors
- Use an object if you need an associative array, not an array. [source]
- Declare all local variables with
varbefore they are used. - Remove trailing commas from array and object definitions, i.e.:
var object = { foo: 'bar' }notvar object = { foo: 'bar', }
Metadata
Use JQuery Metadata to integrate jQuery plugins into Foswiki.LiveQuery
Use JQuery Live Query to initialize your plugin for all html elements of a page. Otherwise content that is loaded asynchronously using ajax won't be initialized. LiveQuery will take care of that automatically. Instead of
$(".jqPluginName").each(function() {
// initializer
});
use
$(".jqPluginName").livequery(function() {
// initializer
});
See JQuery Metadata for a more thorough example of using metadata and livequery