jQuery and Drupal

Courtesy:  Drupal.org

JavaScript closures

It’s best practice to wrap your code in a closure. A closure is nothing more than a function that helps limit the scope of variables so you don’t accidentally overwrite global variables.

// Define a new function.
(function () {
// Variables defined in here will not affect the global scope.
var window = "Whoops, at least I only broke my code.";
console.log(window);
// The extra set of parenthesis here says run the function we just defined.
}());
// Our wacky code inside the closure doesn't affect everyone else.
console.log(window);

A closure can have one other benefit, if we pass jQuery in as a parameter we can map it to the $ shortcut allowing us to use use $() without worrying if jQuery.noConflict() has been called.

// We define a function that takes one parameter named $.
(function ($) {
// Use jQuery with the shortcut:
console.log($.browser);
// Here we immediately call the function with jQuery as the parameter.
}) (jQuery);

The .ready() function also has the ability to alias the jQuery object:

jQuery(document).ready(function($) {
// Code that uses jQuery's $ can follow here.
});

In Drupal 7 jQuery.noConflict() is called to make it easier to use other JS libraries, so you’ll either have to type out jQuery() or have the closure rename it for you. More examples can be found on jQuery’s api site.

Advertisements