davidtgq
davidtgq

Reputation: 4010

A less hacky (but equally short) method to accomplish this switch-like behavior in Javascript?

I'm using this method to find out which tab was clicked and using its id to generate the corresponding element. Each tab has a corresponding function to "make" the content of that tab.

    <li class="nav-item">
      <a class="nav-link tabLeft" data-view="map">Map</a>
    </li>

  $('.tabLeft').each(function () {
    $(this).on('click', function (event) {
      event.preventDefault();
      changeView($(this).data('view'));
    });
  });

  function changeView(type) {
    window['make' + type]();
  }

  function makemap() {//do stuff}

I don't know if any minifiers would be smart enough to rename the id and corresponding function without breaking this. Is there a better method to accomplish this that does not require manually coding a switch?

Upvotes: 0

Views: 46

Answers (1)

Nikola Dimitroff
Nikola Dimitroff

Reputation: 6237

Put the functions in an explicit map (instead of relying on the map that the 'window' object uses to hold the global variables / functions).

var makeFunctions = {
    'Foo': makeFoo,
    'Bar': makeBar
};
makeFunctions[id()]();

Upvotes: 3

Related Questions