I’m very excited about studying Javascript on the mission of expand my knowledges at front-end. The principal goal is use Javascript at my Java back-end projects.
So, two things I really liked on javascript so far is:
- template string;
- spread operator.
The first concept lets a array be used as params of methods, on a very easy and functional way.
The second one helps on format messages that uses dynamics values, as variables. We can just reference the value inside a string pattern, marked with the ` character.
See the example…
As we follow, in the example below we have a constructor that receives three params but on the View we have just one field. Ok, that is not right, but works for now.
<body>
<label>Informações do arquivo</label>
<input class="dados-arquivo" placeholder="formato: nome/tamanho/tipo">
<button onclick="arquivoController.envia()" >Enviar</button>
</body>
class Arquivo {
constructor(nome, tamanho, tipo) {
this._nome = nome;
this._tamanho = tamanho;
this._tipo = tipo;
}
}
So we can use the two concepts above to catch a fancy solution, like this:
envia() {
let dados = this._inputDados.value.toUpperCase().split('/');
let arquivo = new Arquivo(...dados); // the spread operador
console.log(`Dados do arquivo: ${arquivo.nome}, ${arquivo.tamanho}, ${arquivo.tipo}`); // template string
this._limpaFormulario();
}
We still can encapsulate the solution in a helper class, of builder pattern, that generates a static method that returns the model:
ArquivoHelper {
static cria(informacao) {
return new Arquivo(...informacao.toUpperCase().split('/'));
}
}
So, let me move on to the next chapter. So long, fair well.