Outils pour utilisateurs

Outils du site


issue67:tutoriel_-_webdev_p._3

As our CRUD (Create, Read, Update, Delete) continues, we are going to jump right on in. I want to show you how to use JavaScript itself before we rewrite the app with JQuery. Understanding the language is more important than how to use the libraries. One of the first functions we will write is going to be a very well used one. You might actually want to save this for future use. The function needs to look at the document object, search for ids, and return the one you are looking for. First, we start out by creating a function that takes one argument, we’ll call it ge for “get element”. To create a function you simply write: function ge(id) { // code here };

Notre CRUD (Create, Read, Update, Delete ou Créer, Lire, Modifier, Supprimer) se poursuit et nous allons cette fois sauter dedans à pieds joints. Je veux vous montrer comment utiliser JavaScript lui-même avant de réécrire l'application avec JQuery. Comprendre le langage est plus important que la façon d'utiliser les bibliothèques.

L'une des premières fonctions que nous écrirons est vraiment très souvent utilisée. Vous pouvez même en fait vouloir la sauvegarder pour une utilisation future. La fonction doit regarder l'objet document, rechercher des identifiants et retourner celui que vous recherchez. Tout d'abord, nous commençons par créer une fonction qui prend un argument, nous l'appellerons ge pour « get element ». Pour créer une fonction il suffit d'écrire :

function ge(id) {

// votre code ici

};

Now that we have a function, we need to write the code. We are searching the document object model for an id, which the document object has a function for. So let’s bring the results of that function into a variable and return it. // gets an element by its id from the document object model (DOM) function ge(id) { var theElement = document.getElementById(id); return theElement; };

Maintenant que nous avons une fonction, il faut écrire le code. Nous recherchons un identifiant dans le modèle d'objet document et l'objet document possède justement une fonction pour ça. Nous allons rapporter les résultats de cette fonction dans une variable et la retourner.

// Récupère un élément par son id dans le modèle d'objet document (DOM)

function ge(id) {

var theElement = document.getElementById(id);
return theElement;

};

The line that starts with // is called a comment. This line is to help coders keep track of what is going on in their code, and allow them to leave notes for other people using their code. The next thing is that we need to handle the form when the submit button is pressed. First, we need to give an id to the form itself. Let’s call it “ubuVersFrom”. So now, the open form tag should look like this: <form id='ubuVersForm'>. We need to add just one more id to our HTML form. Our submit button should have an id of submit (‘ id='submit' ‘). Your form button should now look like this: <input type=“submit” name=“submit” id='submit' value=“Add” />. So now that we have our form set, we can move back to the JavaScript. The JS contains in its first line an alert to tell us that our JS file is connected. This is pretty annoying when we are testing, so let’s change that to a console log—so we can see it if we want to, and forget about it if we don’t. Next, we create a variable that contains the form element we are going to be using and manipulating later; let’s call that ‘form’. Hint: we created a function to get elements by id a little earlier in this article.

La ligne qui commence par // s'appelle un commentaire. Cette ligne sert à aider les codeurs à garder la trace de ce qui se passe dans leur code, et leur permet de laisser des notes pour d'autres personnes utilisant leur code.

La prochaine chose à faire est de traiter le formulaire lorsque le bouton Envoyer est enfoncé. Tout d'abord, nous devons donner un id au formulaire lui-même. Appelons-le « ubuVersFrom ». Alors maintenant, la balise « open form » (ouvrir formulaire) devrait ressembler à ceci : <form id='ubuVersForm'>. Nous devons juste ajouter un autre identifiant à notre formulaire HTML. Notre bouton Envoyer doit avoir un id d'envoi (« id='submit' »). Votre bouton de formulaire devrait maintenant ressembler à ceci : <input type=“submit” name=“submit” id='submit' value=“Add” />.

Bien, maintenant que nous avons notre formulaire, nous pouvons revenir au JavaScript. Le JS contient sur la première ligne une alerte pour nous dire que notre fichier JS est connecté. C'est assez gênant quand nous testons, nous allons donc changer cela en un affichage dans la console - afin que nous puissions le voir si nous le voulons et l'oublier si nous ne le voulons pas. Ensuite, nous créons une variable qui contient l'élément de formulaire que nous allons utiliser et manipuler par la suite ; appelons-la « form ». Astuce : nous avons créé une fonction pour obtenir des éléments par id un peu plus tôt dans cet article.

So, coding is a lot like logical thinking. Think of how you would tell yourself what needs to happen. If the submit button is pressed, then do process the form. That means we are going to need to have something that attaches a function (let’s call it processForm) to the button. Browsers can be tricky, and there are a few different ways to code some things, and I want to show you good uses of if/else coding… so, we are going to link the function to the button two different ways, but only once. Sounds funny, but it will all make sense. Let’s start out by creating an if/else statement: // Handle form event if (argument) { // do something } else { // do something else };

En fait, le codage est un peu comme la pensée logique. Pensez à comment vous pourriez vous expliquer à vous-même ce qui doit arriver. Si le bouton Envoyer est enfoncé, alors traiter le formulaire. Cela signifie que nous allons avoir besoin d'avoir quelque chose qui attache une fonction (appelons-le processForm) au bouton. Les navigateurs peuvent être tatillons, il existe plusieurs façons de coder certaines choses, et je veux vous montrer les bons usages de codage d'un if/else… nous allons donc relier la fonction au bouton de deux façons différentes, mais une seule fois. Ça a l'air bizarre, mais cela prendra tout son sens bientôt.

Commençons par créer une instruction if/else :

gestion de l'evenement form if (argument) { faire quelque chose

} else {

// faire autre chose

};

If statements look very easy, but it’s also easy to lose track of what is going on, so commenting these heavily from the start is going to save you headaches down the road. I know I want to fall back on the old and reliable addEventListener, this (next page, top left) will then be in our else statement. Earlier, I had you create a variable that holds the form element. It should have looked something like this: var form = ge('ubuVersForm');. This is very useful now, because we can see if the browser let us look at what we can do, what it contains, etc. We are going to look for an attachEvent object within our form element (below). If the browser allows it, let's use it.

Les déclarations « if » ont l'air très faciles, mais il est également facile de perdre de vue ce qui se passe, alors les commenter lourdement dès le départ va vous faire économiser des maux de tête plus tard. Je sais que je dois m'en remettre à la vieille et fiable méthode addEventListener, ceci (page suivante, en haut à gauche) sera donc dans notre déclaration « else ».

Plus tôt, je vous ai fait créer une variable qui contient l'élément formulaire. Cela aurait dû ressembler à quelque chose comme ceci : var form = ge('ubuVersForm');. Ceci est très utile maintenant, parce que nous pouvons voir si le navigateur nous laisse voir ce que nous pouvons faire, ce qu'il contient, etc. Nous allons chercher un objet attachEvent dans notre élément de formulaire (ci-dessous). Si le navigateur le permet, nous allons l'utiliser.

We are almost ready to try everything out, only one problem now. We need to write the processForm function. No sense in adding it to the submit button if it doesn’t exist, right? Start by creating a new function called processForm (above right), with one argument, and make it return false. Now that you have a function, the first thing we want to happen is to stop all default actions the browser knows to take. Again, we only want to do this if the browser allows for it. To do this we use a object called preventDefault. The above code pulls in the form element (as formElement) that you had tied to the event, checks if the browser allows for preventDefault, and does preventDefault if it does. The if statement is on one line in this case because it is such a simple check and run. You could put this on multiple lines, and add an else statement, and maybe console log, if it doesn’t allow preventElement. You could also add console logs to the if/else statement to attach the function to the submit event.

Nous sommes presque prêts à tout essayer ; un seul problème subsiste. Nous devons écrire la fonction processForm. Cela n'a aucun sens de l'ajouter au bouton Envoyer si elle n'existe pas, pas vrai ? Commencez par créer une nouvelle fonction appelée processForm (en haut à droite) avec un argument et faites-lui retourner faux. Maintenant que vous avez une fonction, la première chose à faire est d'arrêter toutes les actions par défaut que le navigateur sait utiliser. Encore une fois, nous voulons faire ceci seulement si le navigateur le permet. Pour ce faire, nous utilisons un objet appelé preventDefault.

Le code ci-dessus récupère l'élément formulaire (comme formElement) que vous aviez lié à l'événement, vérifie si le navigateur permet d'utiliser preventDefault, et appelle preventDefault si c'est le cas. L'instruction if est sur ​​une seule ligne dans ce cas, car il s'agit d'une simple vérification et exécution. Vous pourriez la mettre sur plusieurs lignes et ajouter une instruction else, et éventuellement une ligne d'affichage console, s'il ne permet pas preventElement. Vous pourriez également ajouter des affichages console dans l'instruction if/else pour attacher la fonction à l'événement Envoyer.

We covered quite a bit of stuff this month. The following is an update of how your code should look now. Thank you for following along, I would love to see what you guys have now, or questions/comments that you might have. Feel free to share via twitter @aliendev2 and/or hashtag #FCMWebDev. The full code is on PasteBin at: http://pastebin.com/pV6RGmBg

Nous avons couvert pas mal de choses ce mois-ci. Ce qui suit est une version à jour de ce à quoi votre code devrait ressembler maintenant. Merci de m'avoir suivi, j'aimerais bien voir ce que vous avez maintenant, ou recevoir les questions/commentaires que vous pourriez avoir. N'hésitez pas à partager via twitter @aliendev2 et/ou hashtag #FCMWebDev.

Le code complet est disponible sur Pastebin : http://pastebin.com/pV6RGmBg

issue67/tutoriel_-_webdev_p._3.txt · Dernière modification : 2013/02/17 21:23 de fredphil91