1

For example, let's say you have 8 sections to hide/show and depending on the value of a dropdown, you have to show or hide dynamically from 1 to 8 sections.

1) Is there any better way of doing this than with the approach of the code below?
2) Is this approach acceptable?

$("#dropdown").change(function(){

  var value = this.value;
  var $section1 = $("#section1");
  var $section2 = $("#section2");
  var $section3 = $("#section3");

  $(".section").hide(); //hides all sections

  if(value == "someValue"){
     $section1.show();
     $section2.show();
  } else if (value == "someOtherValue") {
     $section3.show();
  } else {
     $section2.show();
     $section3.show();
  }

  //etc
})

Any other advice that you consider helpful will be appreciated.

  • possible duplicate of [Are there any OO-principles that are practically applicable for Javascript?](http://programmers.stackexchange.com/a/180588/31260) – gnat Jun 01 '15 at 18:06
  • This migration was rejected by Code Review because the code is "hyopthetical". Since it appears to be a well-written question, I'm reopening it on Programmers. /cc @GregBurghardt – Thomas Owens Jun 01 '15 at 19:31

1 Answers1

1

While not really a pattern per se, the main thing I'd do here is separate the code from the data.

By "data", I mean which sections should be shown or hidden for each dropdown item.

var sectionsToShow = {
   item1: [1, 2, 3],
   item2: [2],
   item3: [6, 4, 5],
   ...
};

Then your dropdown handler can (ideally) do something like

sectionsToShow[this.value].forEach(function(sectionToShow) {
   actualSections[sectionToShow].show();
});

to show whichever sections are appropriate for that item.

This way it's much, much easier to reconfigure what sections are shown for each item when you inevitably have to change that mapping somehow.

Ixrec
  • 27,621
  • 15
  • 80
  • 87