Dynamically adding cases to a switch

后端 未结 2 1884
情书的邮戳
情书的邮戳 2020-12-03 08:44

I need to dynamically add cases to a switch. I want the user to be able to add items and every item needs it\'s own switch case.

相关标签:
2条回答
  • 2020-12-03 09:10

    This was the best solution for my needs, but works only with a limited number of custom cases:

    var cases = [false, false];
    
    switch(condition) {
        case cases[0]:
            doStuff();
            break;
        case cases[1]:
            doSomethingElse();
            break;
    }
    

    Now, you can dynamically change the values in the array cases, and the condition in the switch case will be triggered respectively;

    You can click the above snippet to see it working ;)

    const cases = [false, false]; // shall be defined
      
    $('#option1').click( function() {
      cases = [38,37];
    });
    
    $('#option2').click( function() {
      cases = [39,40];
    });
    
    $(window).keydown( function(e) {
      switch (e.keyCode) {
         case 32:
            $("body").append('space<br>');
            break;
         case cases[0]:
            $("body").append((e.keyCode == '38' ? 'UP' : 'RIGHT' ) + '<br>');
            break;
         case cases[1]:
            $("body").append((e.keyCode == '37' ? 'LEFT' : 'DOWN' ) + '<br>');
            break;
    
      }
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    At the begining the switch only take in account SPACE keyCode<br>
    -if you click option1 then it recognize UP and LEFT<br>
    -if you click option2, the aboves are replaced with RIGHT and DOWN<br><br>
    
    <div id='option1'>OPTION 1</div>
    <div id='option2'>OPTION 2</div>

    0 讨论(0)
  • 2020-12-03 09:13

    You can use object with callback functions instead:

    var callbacks = {};
    
    function add(_case, fn) {
       callbacks[_case] = callbacks[_case] || [];
       callbacks[_case].push(fn);
    }
    
    function pseudoSwitch(value) {
       if (callbacks[value]) {
          callbacks[value].forEach(function(fn) {
              fn();
          });
       }
    }
    

    and you can add new entry using:

    add('something', function() {
       // case for something
    });
    
    0 讨论(0)
提交回复
热议问题