How to avoid if-statements in typescript-reactjs?

Question

I have different types of action checks which does different functionalities, simply i made if and else condition to check the action type and do the relevant functionality like the below code snippet

public onMessage = (messageEvent) => {
    if (messageEvent.data.action === 'subscribeTriggers') {
        this.subscribeTriggers(messageEvent);
    } else if (messageEvent.data.action === 'setGlobalFilters') {
        this.setGlobalFilters(messageEvent);
    } else if (messageEvent.data.action === 'getGlobalFilters') {
        this.receiveGlobalFilters(messageEvent);
    } else if (messageEvent.data.action === 'initFromGlobalFilters') {
        this.initFromGlobalFilters(messageEvent);
    }

Is there a better solution to handle this kind of scenario, as i have a potential of having more actions in future where i have to come and change the code again and again, which i felt is inefficient.

Between this onMessage function is used as a event listener for porthole library (Porthole is a small library for secure cross-domain iFrame communication.) which i used to communicate in my react app's iframe

Thanks in advance


Show source
| javascript   | reactjs   | typescript   | if-statement   | porthole.js   2017-01-06 10:01 2 Answers

Answers ( 2 )

  1. 2017-01-06 10:01

    Objects in javascript can be seen as an associative array where the key is the name of the property or the function.

    So, you can make your call like this:

    this[messageEvent.data.action](messageEvent);
    

    WARNING (as noted by Joe Clay): with this syntax, every function of your object this is callable, so it can cause a "security breach", if this contains functions that you do not want to "expose".

  2. 2017-01-06 10:01

    Switch statements are your friend in situations like this:

    public onMessage = (messageEvent) => {
        switch (messageEvent.data.action) {
            case "subscribeTriggers":
                return this.subscribeTriggers(messageEvent);
            case "setGlobalFilters":
                return this.setGlobalFilters(messageEvent);
            case "getGlobalFilters":
                return this.recieveGlobalFilters(messageEvent);
            case "initFromGlobalFilters":
                return this.initFromGlobalFilters(messageEvent);
        }
    }
    

    ADreNaLiNe-DJ's answer would also work if your messageEvent string always matches one of the methods on this - that feels a little hacky to me though, as it would basically mean if you had a this.definitelyNotAnEventHandler, you would still be able to call it through onMessage. I prefer the more explicit approach - that's just a matter of taste, though :)

◀ Go back