vendredi 6 janvier 2017

How to avoid if-statements in typescript-reactjs?

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

Aucun commentaire:

Enregistrer un commentaire