Browse Source

Listing 3.26: general refactoring to reduce redundancy and get a single handler.

Frederic G. MARAND 8 years ago
parent
commit
4351af518a
1 changed files with 27 additions and 27 deletions
  1. 27 27
      Chapter 3/03.js

+ 27 - 27
Chapter 3/03.js

@@ -1,63 +1,63 @@
 $(document).ready(function () {
   'use strict';
 
-  $('#switcher  ').hover(function() {
+  // Enable hover effect on the style switcher
+  $('#switcher').hover(function() {
     $(this).addClass('hover');
   }, function() {
     $(this).removeClass('hover');
   });
-});
-
-$(document).ready(function () {
-  'use strict';
 
+  // Allow the style switcher to expand and collapse.
   var toggleSwitcher = function(event) {
     if (!$(event.target).is('button')) {
       $('#switcher button').toggleClass('hidden');
     }
   };
-
   $('#switcher').on('click', toggleSwitcher);
+
+  // Simulate a click so we start in a collapsed state.
   $('#switcher').click();
 
-  $('#switcher button').click(function () {
+  // The setBodyClass() function changes the page style.
+  // The style switcher state is also updated.
+  var setBodyClass = function (className) {
+    $('body').removeClass().addClass(className);
+
+    $('#switcher button').removeClass('selected');
+    $('#switcher-' +  className).addClass('selected');
+
     $('#switcher').off('click', toggleSwitcher);
 
-    if (this.id === 'switcher-default') {
+    if (className == 'default') {
       $('#switcher').on('click', toggleSwitcher);
     }
+  };
 
-  });
-});
-
-$(document).ready(function () {
-  'use strict';
+  // begin with the switcher-default button "selected"
   $('#switcher-default').addClass('selected');
 
+  // Map key codes to their corresponding buttons to click
+  var triggers = {
+    D: 'default',
+    N: 'narrow',
+    L: 'large'
+  };
+
+  // Call setBodyClass() when a button is clicked.
   $('#switcher').click(function(event) {
     if ($(event.target).is('button')) {
       var bodyClass = event.target.id.split('-')[1];
-
-      $('body').removeClass().addClass(bodyClass);
-
-      $('#switcher button').removeClass('selected');
-      $(event.target).addClass('selected');
+      setBodyClass(bodyClass);
     }
   });
-});
 
-$(document).ready(function () {
-  'use strict';
-  var triggers = {
-    D: 'default',
-    N: 'narrow',
-    L: 'large'
-  };
+  // Call setBodyClass() when a key is pressed.
   // Use keydown/keyup to identify key, keypress to identify resulting letter.
   $(document).keyup(function (event) {
     var key = String.fromCharCode(event.which);
     if (key in triggers) {
-      $('#switcher-' + triggers[key]).click();
+      setBodyClass(triggers[key]);
     }
   });
 });