2

I'm trying to figure out a JavaScript trick that will help make the following block more elegant:

switch(modal) {
    case 'openLoginModal':
        openLoginModal();
    case 'openSignupModal':
        openSignupModal();
    ...
}

This is ultimately for my React app that makes action calls to a Redux store in the following way:

switch(modal) {
    case 'LoginModal':
        this.props.actions.openLoginModal();
    case 'SignupModal':
        this.props.actions.openSignupModal();
    ...
}

Please let me know if you have any insight! Would strongly prefer avoiding the use of the global window.

robinnnnn
  • 1,675
  • 4
  • 17
  • 32
  • 1
    Heavily related: http://stackoverflow.com/questions/359788/how-to-execute-a-javascript-function-when-i-have-its-name-as-a-string Although there are a lot of answers that use `window`, there are also a few solutions that do not. – aug Mar 06 '16 at 00:36
  • 3
    What about `this.props.actions['open' + modal]();` ? – Ivan Sivak Mar 06 '16 at 00:39
  • I'm an idiot, thank you @IvanSivak! – robinnnnn Mar 06 '16 at 01:08
  • Be aware that doing this is going to make tracing your code harder. If it's a small body of code or you're the only one working on it, it's fine, but in a large codebase it'll make it harder for someone unfamiliar with the structure to know where the actions are being invoked from. – S McCrohan Mar 06 '16 at 03:45
  • Don't do this. We don't keep track of program logic elements in JS using strings. Just pass around functions instead, then call them when necessary. if necessary, make a map from string to function and use that. –  Jul 17 '16 at 03:38

0 Answers0