Affichage des articles dont le libellé est javascript. Afficher tous les articles
Affichage des articles dont le libellé est javascript. Afficher tous les articles

lundi 7 janvier 2019

VueJs for the skeptic

Initially, I wanted to write a long article about my skepticism when hearing about shiny piece of tech, especially in the frontend world. I’m very tempted to reject all these frameworks and tools every cool kid is using these days.

Fortunately, I did not and I started using VueJs with Vuex last year. The advantage of all these frameworks (Vue, React, Angular,…) is that they do the DOM and events manipulation for you. To do so, they use an implementation of the good old observer pattern: every change of data in a component or in the global state can be captured so that your UI is automatically updated. They (at least React and Vue) use a DOM abstraction (the virtual DOM) to do this more efficiently than you, I’m curious to see how it works in the source code!

On the other hand, be aware that observed state is not made of plain Javascript objects, but object proxies. Not all action of on the proxy will trigger an update of the observers. Moreover, some of the dependencies you may use can be affected by the way the DOM is manipulated. For instance, with Vue you may want to use Font Awesome Vue component instead of the standard Font Awesome JS bundle. I spent hours to understand why my icons were not updated in some cases!

So, when do you want to use a front end framework? When you plan to update your UI in response to data update and you don’t want your UI logic to be mixed with element creation and event handling. And that’s pretty often!

mercredi 21 octobre 2015

Back to Standards

I’m not so much a front-end guy. I mean, I do love hacking CSS and JS for the browser, but I don’t do it that much as a pro to be aware of all the best practices in this domain. And JS being the top class citizen in the Web this day, this field earned a huge complexity within a blink and I feel a bit overwhelmed. I’m still nicely editing my JS and CSS, refreshing the browser to see the results at the time of preprocessing, transpiling and minifying megabytes of code.

I often wonder if it doesn’t go too far sometimes, to the point that programmers need to reimplement a behavior brought for free by the browser. The must funny example is the use of the prev and next buttons in one page app. But you can also reimplement every form input elements.

That’s what I did, in a project I decided to replace input fields and buttons by plain divs. Because I found that contenteditable attribute was cool. I believed it’ll be easier to style everything.
I realized my mistake lately as getting all in place was a PITA. Moreover, now that I use vimperator, I found out that it would be awful to use the app without mouse if I did not recode the whole shit by myself. So I brought back my text areas and buttons tags. I just “unstyled” them and rework my JS a little bit. I was done in less than a hour.

So here’s the lesson. If you are not a professional front end developer and you need to get things done quickly, consider these points:

  • Keep it stupid simple. Really. Rely on what is offered by the browser. Do not try to be smart because this front end thing is waaaay too complicated for you.
  • It’s hard to admit this because I hate it… But use JQuery as it will eliminate a lot of burden. Coding in vanilla js when you have DOM manipulation is fun until you realize you spend hours to fix a simple UI behavior. And you’ll need few days more to make your fix cross browsers.
  • Really consider to use UI boilerplates like Foundation or Bootstrap. They’re blazingly simple to put in place, provide an elegant look and feel and make your site responsive for free. I know you see the same UI everywhere on the Internet. That’s because the other developers and startupers are like you: they lack skills and time and yet, need to get things done quickly.

This post raises the question of the choice between learning things deeply and get side projects done and be proud of them (where proud can mean getting money). It’ll be a great topic for another post.

jeudi 18 juin 2015

JavaScript without semi colon

As I like programming in Python, using a language that force me to put a semi colon at the end statements bother me a lot. As you may know, the semicolon to end a statement is optional in JavaScript. And you may also know that forgetting it when you need it can hurt you badly.

It turns out that the exceptional cases that prevent the interpretor to consider that a \n is not enough to end a statement are rather simple. Isaac Schlueter recalls them:

In general, \n ends a statement unless:

  1. The statement has an unclosed paren, array literal, or object literal or ends in some other way that is not a valid way to end a statement. (For instance, ending with . or ,.)
  2. The line is -- or ++ (in which case it will decrement/increment the next token.)
  3. It is a for(), while(), do, if(), or else, and there is no {
  4. The next line starts with [, (, +, *, /, -, ,, ., or some other binary operator that can only be found between two tokens in a single expression.

Actually, the most annoying is the 4th one when the next line starts with a paren since it can break immediately-invoked function expressions. But you can easily avoid that in your code with a prefix:

;(function x() { do_sth() })()

Or even:

!function x() { do_sth() }()

Because hey, ExpressionStatements cannot start with function key word.

If you want to respect others code, it might be reasonable to end your file with a semi colon.

This discovery made my day, and I started writing JavaScript code without semi colon with confidence. It's cool.

jeudi 5 février 2015

Playing with localStorage and IE8

I played with localStorage JavaScript API the other day. It allows you to store persistent data, associated with a web site inside your browser. The cool thing is that it is a HTML 5 API compatible with IE8 (which is still the standard at work).

On modern browsers, you can use it on plain html files, even if they're not served by a http server. That's convenient if you want to build something that can be downloaded and use offline. IE8 cannot do that: you need to have you files served by a http server to make localStorage work. If you have Python 3 installed (and you should!), you can serve file painlessly using http.server module from command line:

python -m http.server 8000

You can then connect to http://localhost:8000 and enjoy.

Another nasty stuff that can bite you: IE8 doesn't want you to store undefined values in the local storage. To avoid headache, use it like this:

localStorage.setItem("itemKey", varThatCanBeUndefined || "");

This way, if varThatCanBeUndefined is undefined, the value associated with itemKey will be an empty string. Ugly but it works.

The irony for me is that the concerned piece of code do not work since it is encapsulated in a web site that force IE7 compatibility. Therfore, all my work to make it compatible with IE8 is useless, and I have been forced to add a fall back for localStorage object:

storage = localStorage || { 
   setItem: function(item, value) {}, 
   getItem: function(item) { return "" } 
};

However, the test worth it: I have it to work on Firefox and it was the occasion to play with this nice feature and to write this article!

mercredi 9 avril 2014

Lecture de "Javascript The Good Parts"

Javascript, ce n'est peut-être pas bon mais il faut en manger. J'ai acheté le livre Javascript The Good Parts de Douglas Crockford, homme connu pour être derrière le piquant JSlint. Je pensais y trouver un ensemble de bonnes pratiques et de patterns pour utiliser au mieux ce langage. Je reste un peu sur ma faim.

Le livre balaie les fonctionnalités sympathiques offertes par Javascript comme l'héritage par prototype, l'aspect fonctionnel, les closures, etc. Il décrit davantage les pièges à éviter : les variables globales, l'utilisation du mot clé this, l'instanciation d'objets avec this et autres mots clés qu'il ne faut pas utiliser. En conclusion, l'auteur recommande de se cantonner à un sous ensemble de Javascript, ces fameuses Good parts. Pour ma part, je pense que quelques heures d'utilisation de JSlint et un peu de recherche sur le Net rendent dispensable la lecture de ce livre. Je regrette surtout que le livre n'aborde aucun pattern pouvant permettre de rendre le code plus modulaire, si ce n'est d'encapsuler les fonctions d'un module dans un objet.

jeudi 21 novembre 2013

Tête de node

Le week-end dernier, j'ai enfin testé Node.js histoire de revenir un peu dans la hype. Alors j'ai compilé sur mon vieil ordi de la maison et je me suis lancé. On va dire que j'ai été très agréablement surpris.

Déjà, je pensais que j'allais encore me galérer à la compilation… Et bien non : aucun problème. C'est assez rare pour être signalé.

Ensuite, je tente le hello world de coutume et la création d'un serveur http. Et boum, ça démarre sans aucune latence ! Je ne sais pas comment ils se sont débrouillés mais je m'attendais au moins à quelques dixièmes, comme quand je lance un Python ou, pire, Ruby. Et bien non, ça démarre instantanément.

Sur ce, j'ai regardé un peu ce que l'écosystème proposait. J'ai jeté mon dévolu sur :

  • Express.js : un framework web simple, à la Sinatra qui pourtant à l'air plutôt complet.
  • Mustache : un outil de templating pour le rendu des pages html
  • Less : un outil comme pour faciliter la création de feuilles de style

Et bien, ça donne un début de stack plutôt sympa… à creuser sur un petit projet ?

Je dois dire que j'ai rarement été aussi emballé par une techno. Alors évidemment, il faut aimer Javascript et les callbacks dans tous les sens. Moi j'aime bien.

J'ai utilisé Sass au boulot pour faire des maquettes d'écran mais je vais peut être plutôt me tourner vers Less, qui a en plus la possibilité de tourner directement côté client pour faire de l'interprétation à la volée. Si ça peut permettre d'aller plus vite…