Could someone explain to me the term "Specification Pattern", applied in Javascript?

Asked

Viewed 446 times

8

I did some research on the net, I found this website with valuable information. I work a lot with conditionals using javascript, see an excerpt of my function that receives radiogroup as a parameter and checks whether it was selected yes or no, thus performing the proper tasks:

    var habilitarCampo3 = function(obj,  selectedRadio)
{
    if(selectedRadio.inputValue == "NAO"){
        Ext.getCmp('comJustificativaAviso').setVisible(true);
        if (iAtividade == 7)
        {
            TransitionData2Form.insertMandatory('comJustificativaAviso','Justifique o não desconto do Aviso Prévio!');

        }
    }
    else{
        Ext.getCmp('comJustificativaAviso').setVisible(false);
        TransitionData2Form.removeMandatory('comJustificativaAviso');
        Ext.getCmp('comJustificativaAviso').setValue(Ext.getCmp('procedeJuridico').getValue().inputValue);

    }
};

Sometimes this code stays on the radiogroup object itself, see:

checkSolicitacoesRealizadas = new Ext.form.RadioGroup
         ({
     width:600,
     fieldLabel:'Solicitações foram realizadas',
     labelSeparator: '?',
     id:'checkSolicitacoesRealizadas',
     value:'ZERO',
      listeners:
              {
                change: function(obj, selectedRadio)
                  {
                    if (selectedRadio.inputValue == "NAO")
                     {
                      alert('É obrigatório a geração das solicitações');
                      Ext.getCmp('checkSolicitacoesRealizadas').setValue('ZERO');
                      }

                  }
              },
     items: [
     {boxLabel: '<b style="color:green;" >Sim</b>', name: 'checkSolicitacoesRealizadas-op', inputValue: "SIM"},
     {boxLabel: '<b style="color:green;" >Sim</b>', hidden:true, name: 'checkSolicitacoesRealizadas-op', inputValue: "ZERO"},
     {boxLabel: '<b style="color:red;" >Não</b>', name: 'checkSolicitacoesRealizadas-op', inputValue: "NAO"}
     ]
         });

Here one of the hundreds of conditionals in my code:

 if (Ext.getCmp('tipoRescisao').getValue() == 02 && 
              Ext.getCmp('tipoSolicitacao').getValue().inputValue == 'desligamento')
          {
          if (Ext.getCmp('dataInicioAvisoPrevio').getValue() == '')
              {
                      msgErro += "\n É Obrigatório [Data Início Aviso Prévio]!";
                  }
                }

My question is: Is there any Design Patterns that treats a better way to organize conditional structures, performing some code use while comparing the value of the field? I wanted to organize a dynamic and intelligent structure to perform the value comparisons of form fields. I hope I was clear in the question. Any doubt I improve the question, this is very important to me.

  • I’m ready to signal as "based on opinions" by the part you say "best way to organize structures" but I think we can take advantage of this question, just change this part to "could introduce me some design Partner" so you can see the shapes yourself "different" to do the same thing, and then p/ front you choose the one you find most convenient ;)

  • 1

    "There is some Design Patterns that treats a better way to organize conditional structures, ...." Thank you for your attention. I think that’s a really valid question. When I say "Organize Better," I seek a concept that treats excessive use of if’s, I need an alternative. Your answer does not address this question of if’s.

  • 1

    The question of if, is just make a call to a function from outside the object and make all the validations in another function, the if are not in the answer, but the function call concept yes

  • There is the jQuery library, Angular JS and React that can help you a lot in all this suffering. And there are many more answers to your question on the Mozilla website: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects

3 answers

3


I’ll show you how I work my javascript files:

var ctCompra = {};                                                          // NOVO PADRAO DE DESENVOLVIMENTO        

ctCompra.eventos = function(){                                                      // FUNCAO EVENTOS
    $('#novaautorizacao').button().click(function(){ctCompra.novoFornec();});       // BOTAO NOVA AUTORIZACAO        
    $('#dialog-confirm').hide();                                                    // ESCONDER TELA DE AVISO
    $('button').hide();                                                             // ESCONDER TODOS OS BOTOES
    $("#btEncerrar").button().click(function(){ ctCompra.encerrar(); });            // BOTAO ENCERRAR
    $("#btVoltar").button().click(function(){ ctCompra.retornar(); });              // BOTAO VOLTAR
    $("#mostratodos").button().click(function(){ ctCompra.mostraTodos(); });        // BOTAO MOSTRAR TODOS 
    $("#mostrapendente").button().click(function(){ ctCompra.mostraPendente(); });  // BOTAO MOSTRAR DEPENDENTE        
    $('input:text').setMask();                                                      // CONFIG DE MASKARAS NOS INPUT
    $('#novaautorizacao').show();                                                   // BOTAO NOVA AUTORIZACAO MOSTRAR        
    $('#valor_final').change(function(){ ctCompra.selectPgt(); });                  // CARREGAR PARCELAS
    ctCompra.ajusteSpinner();                                                       // DEPENDENCIA DE EVENTOS
    ctCompra.ajusteTela();                                                          // CHAMADA DA FUNCAO AJUSTE DE TELA
    ctCompra.colorirTr();                                                           // CHAMADA DA FUNCAO COLORIR TR        
};

Come on, I declared a variable called ctCompra it works like a dynamical object, I put the name of the attribute and make it receive a function, ex: ctCompra.eventos = Function(){... when I call ctCompra.events() everything that is inside that Function will be called, note that by "organizing" my screen events are all there, and there inside that function other 3 functions being called:

  • ctCompara.ajusteSpinner();
  • ctCompra.ajusteTela();
  • ctCompra.colorirTr();

And just below that code I write them like this:

ctCompra.ajusteSpinner=function(){                                                  // FUNCAO AJUSTE SPINNER
    ctCompra.parcelas = $('#qtd_parcelas').spinner();                               // BOTAOZINHOS DE INCREMENTAR E DECREMENTAR NO CANTO DO FIELD        
    $('.ui-spinner').removeClass('ui-corner-all').css('float','right');             // STYLE
    $('.ui-spinner').css('margin-right','10px');                                    // STYLE
    ctCompra.parcelas.spinner('disable');                                           // DEFAULT DESABILITADO POIS COMEÇA COM PGT À VISTA QTD=1
    ctCompra.parcelas.spinner({min: 1, max:99});                                    // NÃO ACEITAR VALORES NEGATIVOS NEM ZERO
    $('#select-forma-pgt').change(function(){ ctCompra.selectPgt(); });             // EVENTO SELECIONAR À VISTA OU A PRAZO
    $('.ui-spinner-button').click(function(){ ctCompra.evParcelas(); });            // EVENTO DE CLICAR NA QTD PARCELAS        
};

ctCompra.ajusteTela=function(){                                                     // FUNÇAO AJUSTE DE TELA
    $('#fieldset-menu').css('height','670px');                                      // TELA CONTROLE COMPRA
    $('#fieldset-menu').css('margin','0 70px 10px 0');                              // TELA CONTROLE COMPRA
    $('#div-compromisso').css('padding-top','12px');                                // TELA MENU DE OPÇOES        
};

ctCompra.colorirTr=function(){                                                      // FUNCAO COLORIR TR
    $(".a").mouseover(function(){ $(this).addClass('hover'); });                    // EVENTO MOUSEOVER COLOCAR COR NA TR
    $(".a").mouseout(function(){ $(this).removeClass('hover'); });                  // EVENTO MOUSEOUT RETIRAR COR DA TR  
};

So whenever you need to program inside an "object" not to be mixing the programming do a snippet of code that calls a function from outside so as not to get a lot of Function(){... one inside the other.

  • The question of "programming inside objects" until it’s clear to me. Unfortunately, I couldn’t find the best way to work with conditional structures. This site https://javascriptweblog.wordpress.com/2010/07/26/no-more-ifs-alternatives-to-statement-branching-in-javascript/ helped me to have a different view. Anyway, thank you all.

2

I suggest you stop long enough to reflect on your code and try to separate the responsibilities using OO concepts, there is no problem in using Specification in javascript since Specification is an "abstract" design pattern let’s say so, Specification would be a kind of philosophy rather than a technology of some specific language, understand ?

However it becomes difficult how to answer your question efficiently since more information about what you are doing is required.

if it is an entire javascript application, if it is using javascript as object oriented or event oriented. if it is an application in . NET or Java anyway,

i for example use Specification Pattern no . net next to Domain Driven Design, and Specifications are pretty separate on the domain layer that fires a message queue with an n-layer architecture, until you get to the web view.

0

There are several Design Pattern that serve to improve in some way conditional structure. In their example codes I believe that Pattern but it suits to bring a better intention of these structures would be the MVC Pattern or one of its variations.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.