DEV Community

Cover image for Do you really need a JS Framework in your project?
Tadeu Barbosa
Tadeu Barbosa

Posted on

Do you really need a JS Framework in your project?

When I think about javascript and how it’s giant today, I can’t forget my past with that. I has met js (I’ll call JavaScript just ‘js’, ok?) maybe in 2012–2013… and I remember how was hard to do some things in my web pages. For example: How to submit a form in a page and then clear then? How to select an element by class? And a lot of other things…

If you are a programmer that lived in that times, you can remember the great thing that was jQuery! Oh! jQuery helped me alot! In a form case, I putted it in my code:

$(function() {
  $('#login-form').on('submit', function (e) {
    e.preventDefault();
    //
    var login = $('#login').val();
    var password = $('#password').val();
    doLogin();
    $('#login').val('');
    $('#password').val('');
  });
});
Enter fullscreen mode Exit fullscreen mode

And then my form was be submitted and next all inputs was be cleared like a charm (or not). What is the problem to adding jQuery library in my page if I get what I need? So, somethings need to be observed. jQuery is a library that resolve so many problems with js, resolve browsers incompatibility problems, provide some functionalities that what not possible with js itself; or it was not possible in the past! That is the point!

Nowadays a lot of functionalities has been implemented in the javascript. Many of them was introduced because of jQuery. An example: if you need to get elements by class in jQuery, you just need to call:

$(function() {
  var elements = $('.my-awesome-class'); // get all elements by class
  elements.addClass('another-class'); // add .another-class to each one
});
Enter fullscreen mode Exit fullscreen mode

But… if I tell you that is possible to do it in pure js? 😉 All you need to this is:

const elements = document.querySelectorAll('.my-awesome-class'); // get all elements
elements.forEach(element => {
  element.classList.add('another-class'); // add another-class to each one elements
});
Enter fullscreen mode Exit fullscreen mode

It's work like a charm

You don’t need to use any library to do little jobs! For example, if you need to work with forms like the first example:

document.querySelector('#login-form').addEventListener('submit', function(e) {
  e.preventDefault();
  //
  const login = document.querySelector('#login').value;
  const password = document.querySelector('#password').value;
  doLogin();
  document.querySelector('#login').value = '';
  document.querySelector('#password').value = '';
}
Enter fullscreen mode Exit fullscreen mode

Can you see it? 😃 Of course: this code can be much better, but to exemplify it’s enough.

My problem here, and what I want to show you is not about jQuery. This was a great and awesome project that changed how we see web development. Not, jQuery it’s not the problem. A many of projects still using this.

What I really want to show you is: You don’t need to a JS Library for all your projects. Many times you just to write a simple (and powerful) js file and it’s all.

I remember when I knew AngularJS (Angular 1), and how I used it to make anything that I needed to do. When I wrote controllers and services just ’cause I could. Not ’cause I was really needing it, but ’cause I could. Or when I met VueJS and used just for get a input name and show it for the user.

Do you don’t believe in me? See that code in one of my old codes. This is the code to make a login:

$(function(){
  $('#entrar').live('click',function(){
    $_login();
  });
  $('input').live('keypress',function(e){
    if(e.which==13){
      $_login();
    }
  });
  function $_login(){
    var login = $('input:eq(0)'),
    senha = $('input:eq(1)'),
    login_val = $.trim( login.val() ),
    senha_val = $.trim( senha.val() );
    if(!login_val){
      alert('Insira um login!');
      login.focus();
    } else if(!senha_val){
      alert('Insira uma senha!');
      senha.focus();
    } else {
      $.post('action.php',{action:'login', login:login_val, senha:senha_val},function(ret){
        switch(ret){
          case 'nao':
            alert('Usuario nao existe!');
            break;
          case 'senha':
            alert('Senha incorreta!');
            senha.focus();
            break;
          case 'logado':
            location.href = 'index.php';
            break;
        }
      });
    }
  }
});
Enter fullscreen mode Exit fullscreen mode

I’ll try to create a code based on this one using pure js. For AJAX response I’ll use axios library, a small library. But it’s totally possible to made with pure js.

<form id="form-login">
    <div>
      <label for="login">Login:</label>
      <input type="text" name="login" id="login" placeholder="Login" />
    </div>
    <div>
      <label for="login">Login:</label>
      <input type="password" name="password" id="password" placeholder="Password" />
    </div>
    <div>
      <button type="submit">Entrar</button>
    </div>
</form>

<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.2/axios.min.js"
  integrity="sha256-T/f7Sju1ZfNNfBh7skWn0idlCBcI3RwdLSS4/I7NQKQ=" crossorigin="anonymous"></script>
Enter fullscreen mode Exit fullscreen mode
const formLogin = document.querySelector('#form-login');
const loginElm = document.querySelector('#login');
const passwordElm = document.querySelector('#password');

formLogin.addEventListener('submit', onLoginSubmit);

function onLoginSubmit(event) {
  event.preventDefault();
  //
  const login = loginElm.value.trim();
  const password = passwordElm.value.trim();
  if (!login) {
    alert('Verify your login!');
    return loginElm.focus();
  }
  if (!password) {
    alert('Verify your password!');
    return passwordElm.focus();
  }
  //
  const payload = {
    'login': login,
    'password': password,
  };
  axios.post('action.php', payload)
  .then(() => {
    location.href = 'index.php';
  })
  .catch((response) => {
    alert(response.error);
  });
}
Enter fullscreen mode Exit fullscreen mode

It’s not the best way to do this, this code can be much better, but serves that purpose.


It’s all that I want to show from now. Have many things that I could tell you and I wish to do it in the future. I wish that this little post can help you!


Photo by Joshua Aragon on Unsplash

Top comments (4)

Collapse
 
raphaeldasilva profile image
Raphael da Silva

Eu parei de focar no front-end desde 2014, nunca acompanhei o hype dos frameworks e isso me deixava bastante perdido. Confesso que até hoje ainda uso o velho Jquery.

O que eu tentei fazer foi mudar a estruturação do código para que ficasse mais maduro e organizado. Por isso, adoto a modulariação com IIFEs. Enfim, passei a me preocupar mais com a estrutura do que com framework.

Collapse
 
tadeubdev profile image
Tadeu Barbosa

Sim, compreendo, Rafael. A ideia é que a um tempo atrás precisava de um framework como JQuery pra fazer umas coisas que o javascript não dava suporte nativamente. Tem muita gente, e eu já fui assim, que inclui uma biblioteca (às vezes não é nem a versão minificada), pra fazer uma tarefa simples que o javascript puro poderia dar conta. Entende? Um exemplo seria essa validação do formulário nos exemplos do post.
Framework javascript surge aos montes todos os dias 😅. Se a gente for acompanhar todos... Por isso que ficar um tempo sem mexer com a linguagem faz a gente ficar perdido.
Eu uso framework no meu dia a dia, o vuejs por exemplo, uso de mais. Mas se a coisa for um simples clique num botão, ou esconder uma div... javascript puro resolve 😃

Collapse
 
raphaeldasilva profile image
Raphael da Silva • Edited

Entendo. Tem coisa que é complexidade adicional usar um framework mesmo. Front-end não é o que considero meu forte, até porque eu aprendi a programar com Jquery e só depois dei uma mexida com javascript puro.

Por gostar de orientação a objetos e estruturar as coisas, dei uma olhada no uso de prototype para simular classes (antes disso ser adicionado no ES6). Escrevi sobre isso.

Valeu pelo feedback.

* Meu nome é com PH :)

Thread Thread
 
tadeubdev profile image
Tadeu Barbosa

Ótimo! Vou ler o seu artigo! :)