开发者

how to stop writing repeated code

开发者 https://www.devze.com 2022-12-10 21:56 出处:网络
Hi I was just wondering how I can change the code below to less lines of code, it contains a lot of repeated lines,

Hi I was just wondering how I can change the code below to less lines of code, it contains a lot of repeated lines,

basically what it does it swaps images and make them zoom in,

any help would be appreciated,

 // JavaScript Document
$(function() {

    var fullWidth = 1500; // Width in pixels of full-sized image
    var fullHeight = 2000; // Height in pixels of full-sized image
    var thumbnailWidth = 327;  // Width in pixels of thumbnail image
    var thumbnailHeight = 480;  // Height in pixels of thumbnail image

    // Set size of div
    $('.big_product').css({
                    'width': thumbnailWidth+'px',
                    'height': thumbnailHeight+'px'
    }); 

  //on page load hide small product2 and small product3
  $('#small_product2,#small_product3').hide();

  var selected_color;
  //get the selected color
  $('#colors option').click(function() {
      selected_color = $('#colors option:selected').text().toLowerCase();

      //show the relevant product according to selected color
      if(selected_color == 'navy') {              
          $('#small_product2,#small_product3').hide();
          $('#small_product1').show();
      }

     else if(selected_color == 'grey') {
          $('#small_product1,#small_product3').hide();
          $('#small_product2').show();
      }

      else if(selected_color == 'black') {
          $('#small_product1,#small_product2').hide();
          $('#small_product3').show();
      }
 });

//hide the full-sized(the largest) pictures
$('#full1-1,#full1-2,#full1-3').hide();

//hide the thumbnails
$('#thumbnail1-1,#thumbnail1-2,#thumbnail1-3').hid开发者_如何学Goe();

//when the first small pic is clicked
$('#small_product1-1').click(function() {
    $('#main_product,#big_product1-2,#big_product1-3').hide();
    $('#big_product1-1,#thumbnail1-1').show();
});

// Toggle full and thumbnail pictures on click
$('#big_product1-1').click(function() {
    $('#thumbnail1-1').toggle();
    $('#full1-1').toggle();                 
});

// Do some calculations
    $('#big_product1-1').mousemove(function(e) {
        var mouseX = (e.pageX-400) - $(this).attr('offsetLeft'); 
        var mouseY = (e.pageY-400) - $(this).attr('offsetTop'); 

        var posX = (Math.round((mouseX/thumbnailWidth)*100)/100) * (fullWidth-thumbnailWidth);
        var posY = (Math.round((mouseY/thumbnailHeight)*100)/100) * (fullHeight-thumbnailHeight);

        $('#full1-1').css({
            'left': '-' + posX + 'px',
            'top': '-' + posY + 'px'
        });
  });

//when the second small pic is clicked
$('#small_product1-2').click(function() {
    $('#main_product,#big_product1-1,#big_product1-3').hide();
    $('#big_product1-2,#thumbnail1-2').show();
});

// Toggle full and thumbnail pictures on click
$('#big_product1-2').click(function() {
    $('#thumbnail1-2').toggle();
    $('#full1-2').toggle();                 
});

// Do some calculations
    $('#big_product1-2').mousemove(function(e) {
        var mouseX = (e.pageX-400) - $(this).attr('offsetLeft'); 
        var mouseY = (e.pageY-400) - $(this).attr('offsetTop'); 

        var posX = (Math.round((mouseX/thumbnailWidth)*100)/100) * (fullWidth-thumbnailWidth);
        var posY = (Math.round((mouseY/thumbnailHeight)*100)/100) * (fullHeight-thumbnailHeight);

        $('#full1-2').css({
                        'left': '-' + posX + 'px',
                        'top': '-' + posY + 'px'
        });
  });

//when the third small pic is clicked
$('#small_product1-3').click(function() {
    $('#main_product,#big_product1-1,#big_product1-2').hide();
    $('#big_product1-3,#thumbnail1-3').show();
});

// Toggle full and thumbnail pictures on click
$('#big_product1-3').click(function() {
    $('#thumbnail1-3').toggle();
    $('#full1-3').toggle();                 
});

// Do some calculations
    $('#big_product1-3').mousemove(function(e) {
        var mouseX = (e.pageX-400) - $(this).attr('offsetLeft'); 
        var mouseY = (e.pageY-400) - $(this).attr('offsetTop'); 

        var posX = (Math.round((mouseX/thumbnailWidth)*100)/100) * (fullWidth-thumbnailWidth);
        var posY = (Math.round((mouseY/thumbnailHeight)*100)/100) * (fullHeight-thumbnailHeight);

        $('#full1-3').css({
            'left': '-' + posX + 'px',
            'top': '-' + posY + 'px'
        });
  });
});


You already saw, that there are some passages in your code that look very similar. Just try to find the little differences and see if you can abstract further. So instead of writing 3x

// Do some calculations
$('#big_product1-2').mousemove(function(e) {
  var mouseX = (e.pageX-400) - $(this).attr('offsetLeft'); 
  var mouseY = (e.pageY-400) - $(this).attr('offsetTop'); 

  var posX = (Math.round((mouseX/thumbnailWidth)*100)/100) * (fullWidth-thumbnailWidth);
  var posY = (Math.round((mouseY/thumbnailHeight)*100)/100) * (fullHeight-thumbnailHeight);

  $('#full1-2').css({
    'left': '-' + posX + 'px',
    'top': '-' + posY + 'px'
  });
});
$('#big_product1-2').click(function() {
$('#thumbnail1-2').toggle();
$('#full1-2').toggle(); 

you could write

var doStuff = function(id) {
   $('#big_product'+id).mousemove(function(e) {
      var mouseX = (e.pageX-400) - $(this).attr('offsetLeft'); 
      var mouseY = (e.pageY-400) - $(this).attr('offsetTop'); 

      var posX = (Math.round((mouseX/thumbnailWidth)*100)/100) * (fullWidth-thumbnailWidth);
      var posY = (Math.round((mouseY/thumbnailHeight)*100)/100) * (fullHeight-thumbnailHeight);

      $('#full'+id).css({
        'left': '-' + posX + 'px',
        'top': '-' + posY + 'px'
      });
    });
$('#big_product'+id).click(function() {
$('#thumbnail'+id).toggle();
$('#full'+id).toggle(); 
}

and call it with doStuff('1-2'); and so on...


This part:

//show the relevant product according to selected color
if(selected_color == 'navy') {                          
    $('#small_product2,#small_product3').hide();
    $('#small_product1').show();
}
else if(selected_color == 'grey') {
    $('#small_product1,#small_product3').hide();
    $('#small_product2').show();
}
else if(selected_color == 'black') {
    $('#small_product1,#small_product2').hide();
    $('#small_product3').show();
}

could be written as:

//show the relevant product according to selected color
$('#small_product1,#small_product2,#small_product3').hide();
if(selected_color == 'navy') {                          
    $('#small_product1').show();
}
else if(selected_color == 'grey') {
    $('#small_product2').show();
}
else if(selected_color == 'black') {
    $('#small_product3').show();
}

and the repeated parts:

//when the third small pic is clicked
// Toggle full and thumbnail pictures on click
// Do some calculations

could be broken out to a function.


I like table driven code. It means the answer scales very nicely when you add a fourth or fifth control. It also nicely separates the association between data from the implementation. I don't have tome to run the below (and my PHP is weak) so it is pseudocode, but hopefully it will pass on the idea.

array control_colour_map = {
    { 'navy', 'small_product1',
    { 'grey', 'small_product2',
    { 'black', 'small_product3' }

for item in control_colour_map
{
    if( selected_colour = item.first )
        item.second.show()
    else
        item.second.hide()
}

If there were a show/hide function taking a boolean parameter it could be even shorter

for item in control_colour_map
    item.second.show( selected_colour = item.first )


It is very fortunate that jQuery base its operation on string (selector) so you can do quite a lot of tricks with it.

The following is the code what I apply the trick I can think of in it. Since I don't have your HTML code too and I am lazy too create one so I can't test this code. Please forgive me if I am wrong in the code. :-p

Here is the code:

// JavaScript Document

function swapSmallProduct(ShowID, MaxID) {
    var ToShow = "#small_product"+ShowID;
    $(ToShow).show();
    // Use loop or array to customize the id
    for(i = 1; i <= MaxID; i++) {
        var IDToHide = ((ShowID + i) % MaxID);
        var ToHide = "#small_product"+IDToHide;
        $(ToHide).hide();
    }
}

function hideAll_Full_and_Thumbnail(MaxID) {
    // Use loop or array to customize the id
    for(i = 1; i <= MaxID; i++) {
        $('#full1-'     +i).hide();
        $('#thumbnail1-'+i).hide();
    }
}

function toggle_BigProduct(ID, MaxID) {
    var ToShow = "#big_product1-"+ShowID+",#thumbnail1-"+ShowID;
    $(ToShow).show();

    $('#main_product').hide();
    for(i = 1; i <= MaxID; i++) {
        var IDToHide = ((ShowID + i) % MaxID);
        var ToHide = "#big_product"+IDToHide;
        $(ToHide).hide();
    }
}
function toggle_Full_and_Thumbnail(ID) {
    // Use function to generalize the id
    $('#thumbnail1-'+ID).toggle();
    $('#full1-'     +ID).toggle();
}

function getNumID(StrID) {
    var RegEx = /[0-9]+$/i;
    var Match = RegEx.exec(StrID);
    if (Match == null)
        return "";

    return 0+Match[0];
}


$(function() {

    var maxID = 3;
    var fullWidth = 1500; // Width in pixels of full-sized image
    var fullHeight = 2000; // Height in pixels of full-sized image
    var thumbnailWidth = 327;  // Width in pixels of thumbnail image
    var thumbnailHeight = 480;  // Height in pixels of thumbnail image

    // on page load hide small product2 and small product3
    $('#small_product2,#small_product3').hide();

    // Set size of div
    $('.big_product').css({
        'width':  thumbnailWidth +'px',
        'height': thumbnailHeight+'px'
    });

    var selected_color;
    //get the selected color
    $('#colors option').click(function() {
        selected_color = $('#colors option:selected').text().toLowerCase();
        // show the relevant product according to selected color
        // Use loop or array to customize the id
        if     (selected_color == 'navy')  swapSmallProduct(1, maxID);
        else if(selected_color == 'grey')  swapSmallProduct(2, maxID);
        else if(selected_color == 'black') swapSmallProduct(3, maxID);
    });

    // Use function to generalize the id
    hideAll_Full_and_Thumbnail(maxID);

    // Use prefix selector
    $(<i>"[id^='small_product1-']"</i>).click(function() {
        // and extract the ID to customize each click function
        var aNumID = getNumID($(this).attr("id"));
        // Use function to generalize the id
        toggle_BigProduct(aNumID, MaxID);
    }
    // Use prefix selector
    $(<i>"[id^='big_product1-']"</i>).click(function() {
        // and extract the ID to customize each click function
        var aNumID = getNumID($(this).attr("id"));
        // Use function to generalize the id
        toggle_Full_and_Thumbnail(aNumID);
    }

    // Use prefix selector
    $(<i>"[id^='big_product1-']"</i>).mousemove(function(e) {
        // and extract the ID to customize each click function
        var aNumID = getNumID($(this).attr("id"));

        var mouseX = (e.pageX-400) - $(this).attr('offsetLeft'); 
        var mouseY = (e.pageY-400) - $(this).attr('offsetTop'); 

        var posX = (Math.round((mouseX/thumbnailWidth )*100)/100) * (fullWidth  - thumbnailWidth);
        var posY = (Math.round((mouseY/thumbnailHeight)*100)/100) * (fullHeight - thumbnailHeight);

        $('#full1-'+aNumID).css({
            'left': '-' + posX + 'px',
            'top':  '-' + posY + 'px'
        });
    });
}

}

See the bold part.

The size of code now may not that smaller but it is now more scallable (as you can have more than 3 and the code will not grow) and it is now less error-prone.

Hope I give you some idea.


I advice you to read clean code. It got allow of eye openers

0

精彩评论

暂无评论...
验证码 换一张
取 消