Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

355
Visualizações
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

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

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".

over 4 years ago · Santiago Trujillo Relatório

0

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 :)

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda