Search code examples
jquerycode-organizationmodule-pattern

Understand jQuery Tutorial Module Pattern example


Considering the last code fragment (reported below) about module pattern published in the Code Organization section of the Learning Center, I'm trying to understand some aspect of the module in the example:

  • The variable declarations ($items, $container...) are separated by ; while the function declarations (createContainer, buildUrl, showItem, ....) are separated by ,. Why? Is there a bracket problem?
  • Why the name of the first three variables ($items, $container and $currentItem) starts with $? Does this imply a naming convention (since javascript allows the character $) used to identify a DOM fragment variable or is there some other reason?
  • Why the function createContainer is declared using var while the other functions (buildUrl, showItem,...) doesn't have var?

// Using the module pattern for a jQuery feature $( document ).ready(function() {

var feature = (function() {

var $items = $("#myFeature li");
var $container = $("<div class='container'></div>");
var $currentItem = null;
var urlBase = "/foo.php?item=";
var createContainer = function() {
  var $i = $( this );
  var $c = $container.clone().appendTo( $i );
  $i.data( "container", $c );
},
buildUrl = function() {
  return urlBase + $currentItem.attr("id");
},
showItem = function() {
  var $currentItem = $( this );
  getContent( showContent );
},
showItemByIndex = function( idx ) {
  $.proxy( showItem, $items.get( idx ) );
},
getContent = function( callback ) {
  $currentItem.data("container").load( buildUrl(), callback );
},
showContent = function() {
  $currentItem.data("container").show();
  hideContent();
},
hideContent = function() {
  $currentItem.siblings().each(function() {
    $( this ).data("container").hide();
  });
};
$items.each( createContainer ).click( showItem );

return {
  showItemByIndex: showItemByIndex
};

})();

feature.showItemByIndex( 0 );
});

Solution

    1. You can declare variables in multiple statements or only in 1, is your decision. (var x;var y; versus var x,y;). There is no difference as far as I know.

    2. Starts with a $ : is at the developers choice, for PHP programmers it lookes better, does not affect the variables, is nothing special, just a naming convention. I don't use it, and I don't recommend it, it only makes your code look worst, and if you use jQuery will give you more headeaches.

    3. see point 1 (it has "var", but it is at the begining of the statement) :

      var createContainer = function() {...},buildUrl = function() { ... },showItem = function() {... },showItemByIndex = function( idx ) {...}...;

    See more details at http://www.w3schools.com/js/js_variables.asp and http://www.wikihow.com/Declare-a-Variable-in-Javascript