Outils pour utilisateurs

Outils du site


issue70:developpement_web_-_crud

Table des matières

1

This month, we are going to talk about localStorage. This localStorage is built into the browsers for you to use to hold information that you can retrieve later. With that said, other websites can also use it. When you are writing your code, you should write it with that in mind. localStorage is a pretty powerful tool if you learn how to use it properly. It can allow you to give the user a place to hold data without holding it on your website. localStorage works by using key/value pairs. This basically means this = that, key = value, or itemName = itemInfo. The value can hold only strings of information, but there are ways to get around that if you want to hold a set of strings. That is what we will be doing. Check out your own localStorage, just run a console.log(localStorage);. There are other ways of checking your localStorage, however they are not very reliable. Doing it this way, you know you are going to have your answer returned to you.

Ce mois-ci, nous allons parler de localStorage. localStorage est intégré dans les navigateurs pour que vous puissiez y stocker des informations que vous pourrez récupérer plus tard. Celà dit, des sites web peuvent également l'utiliser. Lorsque vous écrirez votre code, vous devrez l'écrire avec cela à l'esprit.

localStorage est un outil très puissant si vous apprenez à l'utiliser correctement. Il peut vous permettre de fournir à l'utilisateur un endroit pour stocker des données sans les mettre sur votre site web. localStorage fonctionne avec des paires clé/valeur. Par exemple, ceci = cela, clé = valeur, ou nomElement = infoElement. La valeur peut contenir uniquement une chaîne de caractères, mais il y a des façons de contourner cela pour stocker un ensemble de chaînes. C'est ce que nous allons faire.

Découvrez votre propre localStorage, il suffit d'exécuter un console.log(localStorage);. Il y a d'autres façons de voir votre localStorage, mais elles ne sont pas très fiables. En exécutant un console.log(localStorage);, vous savez que vous allez avoir votre réponse.

2

We are going to make a lot of changes to your js file to adapt it for use of local storage to hold our Ubuntu Versions. Since we will be doing so many changes, we will go through the whole main.js file with changes already added. Before we go into the main.js file, we are going to add a button in the index.html file. I added my button after the form section, and before the list. Here is that code: <section> <button onClick='clearLocalStorage()'>Clear localStorage</button> </section>

Nous allons faire beaucoup de changements à votre fichier js pour l'adapter à l'utilisation du stockage local pour conserver nos versions d'Ubuntu. Comme nous allons faire de nombreux changements, nous allons passer en revue l'ensemble du fichier main.js avec les changements déjà ajoutés.

Avant d'aller voir le fichier main.js, nous allons ajouter un bouton dans le fichier index.html. J'ai ajouté mon bouton après la section form, et avant la liste. Voici ce code :

<section>

  <button onClick='viderStockageLocal()'>Vider stockage local</button>

</section>

3

This button is pretty simple. The onClick function, as an attribute, will tell javascript to run whatever is in the attribute. The text between the button tag will be what is displayed inside the button. Now that we have a “Clear localStorage” button, let’s move on to the fun JavaScript. Starting from the beginning, we have a console log to tell us that our js file is connected. If the functions do not contain anything new, I will just be mentioning them with their code. console.log('js connected');

Ce bouton est assez simple. La fonction onClick, comme attribut, indique à JavaScript d'exécuter tout ce qui est dans l'attribut. Le texte entre les balises de bouton sera affiché sur le bouton.

Maintenant que nous avons un bouton « Vider stockage local », amusons-nous avec JavaScript. En partant du début, nous avons un message console pour nous dire que notre fichier js est connecté. Si les fonctions ne contiennent rien de nouveau, je ne ferai que les mentionner avec leur code.

console.log('js connecté');

4

Next we have our get element function “ge”, so that we can easily grab elements from the DOM by their ID. function ge(id) { var theElement = document.getElementById(id); return theElement; };

Ensuite, nous avons notre fonction de récupération d'élément « ge », qui nous permet de récupérer facilement des éléments du DOM par leur ID.

function ge(id) {

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

};

5

The processForm function changes a little bit: http://pastebin.com/HuLiH3tw First in the processForm function, we are preventing the default behavior of the form and console logging, to let us know what is going on in the js as it happens. The next console log is making sure we know what our elements are and what we can do with them. This next portion of the function is checking to make sure our form fields are not blank, and letting the user know if they are. If they are not blank, then we are calling a function to store the data, and then display the data. The display data function will be a new function that we can call on anytime something happens to the data. After we are done working with the data, we are going to clear the fields using ge(‘id’).value = ‘’;. Last but not least, we make the function return false to make sure the default behavior is prevented.

La fonction processForm change un peu: http://pastebin.com/HuLiH3tw

D'abord dans la fonction processForm, nous empêchons le comportement par défaut du formulaire et de la console, pour qu'on puisse voir ce qui se passe dans le js au fur et à mesure. Le message suivant dans la console sert à s'assurer que nous savons quels sont nos éléments et ce que nous pouvons faire avec eux.

La partie suivante de la fonction sert à vérifier que nos champs de formulaire ne sont pas vides et à avertir l'utilisateur s'ils le sont. S'ils ne sont pas vides, alors nous appelons une fonction pour stocker les données, puis les afficher. La fonction d'affichage des données sera une nouvelle fonction que nous pouvons appeler lorsque les données sont modifiées.

Quand nous avons fini de travailler avec les données, nous allons effacer les champs à l'aide de ge('id').value = '';. Pour terminer, la fonction renvoie « faux » pour empêcher le comportement par défaut.

6

The storeData function also has had a few changes made to it: http://pastebin.com/ef2Q7py4 The first thing we are going to do is create a key. This if statement is asking if the submit button has a key attached to it: • If it doesn’t, it will create an ID. The ID it is creating will always start with ubuVers. This is so we can make sure the data we are about to pull back in and display, actually belongs to us. The second part of the key is a random number multiplied by 10000001. This way, if the random number comes back as 3, it will still have a long enough string of numbers to be unique. • If it does have a submit button, it will set the ID to that key. That sets us up for editing the versions in our list if we need to. We will see that action a little bit later.

La fonction storeData a également subi quelques changements : http://pastebin.com/ef2Q7py4

La première chose que nous allons faire est de créer une clé. L'instruction « if » demande si le bouton submit a une clé qui lui est rattachée : • si ce n'est pas le cas, elle va créer un ID, qui commencera toujours par ubuVers. En effet, nous pouvons ainsi nous assurer que les données que nous sommes sur le point de récupérer et d'afficher nous appartient bien. La deuxième partie de la clé est un nombre aléatoire multiplié par 10000001. De cette façon, si le nombre aléatoire vaut 3, cela formera une assez longue chaîne pour être unique ; • sinon, elle va définir l'ID égal à cette clé-là. Nous sommes alors prêts à éditer les versions dans notre liste, si nous en avons besoin. Nous verrons cette action un peu plus tard.

7

The next portion of this function is giving variable names to the form elements, and adding their values into a dictionary, nothing too special there. After we console log those values to make sure we are doing what we think we are doing, we have a very special line of code. “localStorage.setItem(id, JSON.stringify(ubuVersDict));” is a line that is actually setting information to localStorage. If the ID already exists in storage, it will overwrite the information (hints the editing), and, if not, it will make a new entry. The second bit of information getting passed to setItem() is the data we put the version and release into. The data type for that is known as many things, but, in JavaScript’s case, it is called json. Using the JSON object, we are going to “stringify” the information going into the localStorage. This means that it is creating a string out of the json object. This is important if you want to be able to access that data later, otherwise it will go in as [object Object].

La suite de cette fonction donne des noms de variables aux éléments de formulaire et ajoute leurs valeurs dans un dictionnaire ; rien de bien spécial. Après avoir écrit ces valeurs dans la console pour être sûrs que nous faisons ce que nous pensons que nous faisons, nous avons une ligne de code très particulière, « localStorage.setItem(id, JSON.stringify(ubuVersDict)); » est une ligne qui, en fait, définit des informations dans localStorage. Si l'ID existe déjà dans le stockage, elle écrasera les informations (donc de l'édition) et, sinon, elle créera une nouvelle entrée.

La seconde information passée à setItem() représente les données dans lesquelles nous mettons le numéro de version et son nom. Le type de données utilisé pour cela peut porter plusieurs noms, mais en JavaScript on l'appelle JSON. Utiliser un objet JSON permet de « chaînifier » les informations entrant dans le localStorage. Cela signifie qu'on crée une chaîne à partir de l'objet JSON. Ceci est important si vous voulez être en mesure d'accéder à ces données plus tard, sinon elles seront sous la forme [objet Objet].

8

Last up in the function are two lines that can make your life very difficult if you forget them. The first is to console log the localStorage object so debugging is easier if we need to. The second line is to make sure the submit button has a value of “Add”. The “Add” value on the submit button is another one of those things that goes with editing data later. The displayData function is a very important piece of this puzzle. As I told you earlier, this will fire every time something happens to our data. Let’s take a look at that now: http://pastebin.com/TPqq31ye The first thing we are doing in this function is to clear out everything in our list. innerHTML is a great function if you need to clear or set information inside of an HTML element. Immediately after clearing our list, we are going to jump into going through the localStorage data.

À la fin de la fonction se trouvent deux lignes qui peuvent vous rendre la vie très difficile si vous les oubliez. La première consiste à écrire dans la console l'objet localStorage pour que le débogage soit plus facile s'il est nécessaire. La deuxième ligne sert à s'assurer que le bouton submit a une valeur « Ajouter ». La valeur « Ajouter » sur le bouton submit est l'une des choses qui concernera l'édition des données plus tard.

La fonction displayData est une pièce très importante de ce puzzle. Comme je vous l'ai dit plus tôt, elle se déclenchera à chaque fois que nos données sont modifiées. Jetons-y un œil maintenant : http://pastebin.com/TPqq31ye

La première chose que nous faisons dans cette fonction est de vider notre liste. innerHTML est une super fonction si vous avez besoin d'effacer ou de placer des informations à l'intérieur d'un élément HTML. Immédiatement après avoir vidé notre liste, nous allons passer au parcours des données du localStorage.

9

First up is to check if it is empty: • If it is, we are going to let the user know that there is nothing being stored. Otherwise, we are going to look inside it. localStorage.length is counting how many items are within the array; if it is 0, it is empty. • If it is not empty, we have the opportunity to go and check things out. The first thing we do is loop through all of the items. We will need to set a variable for the key and the object inside the value. These variables are very important to the whole function and the whole project. The key variable is simply grabbing the key from local storage by using the key object (localStorage.key(i)). The i being passed to the key object is the integer that is being used to count through the for loop. The value variable is passing the key variable through the getItem object, which returns the information stored in localStorage for the given key. The third variable, obj, is changing the stringified information back to JSON data. JSON.parse will change any stringified JSON data back to valid JSON we can access again.

Il faut d’abord vérifier s'il est vide : • Si c'est le cas, nous allons indiquer à l'utilisateur que rien n'est stocké. Sinon, nous allons regarder à l'intérieur. localStorage.length compte le nombre d'éléments dans le tableau ; si ça donne 0, il est vide. • S'il n'est pas vide, nous pouvons aller vérifier le contenu. Nous faisons d'abord une boucle sur tous les éléments. Nous aurons besoin de définir une variable pour la clé et l'objet à l'intérieur de la valeur. Ces variables sont très importantes pour l'ensemble de la fonction et du projet. La variable clé récupère simplement la clé depuis le stockage local à l'aide de l'objet clé (localStorage.key(i)). Le i en paramètre de l'objet key est l'entier qui est utilisé pour compter pendant la boucle.

La variable de valeur passe la clé à l'objet getItem, qui renvoie l'information stockée dans localStorage pour la clé donnée. La troisième variable, obj, modifie les informations « chaînifiées » pour les remettre sous forme de données JSON. JSON.parse va changer toutes les données JSON « chaînifiées » en JSON valide pour qu'on puisse y accéder à nouveau.

10

The next if statement is checking to see if the key is one of our “ubuVers” keys. Using substring(x,y) is a way to grab a part of a string. x being the character you would like to start with, and y being the character you would like to end on. The ending character is not included in the grabbed substring. For example, substring (0,2) of the word cat, will return “ca”. the 0 character being c, and the 2 being t. If the key does start with “ubuVers”, it is one of ours, and we need to process it. The first thing we are going to do is console log the key and value out for debugging, then we are going to make a whole bunch of variables.

La prochaine instruction if sert à vérifier si la clé est l'une de nos clés « ubuVers ». Utiliser substring(x,y) permet d'extraire une partie d'une chaîne. x étant le caractère que vous souhaitez au début et y, le caractère que vous souhaitez à la fin. Le caractère de fin n'est pas inclus dans la chaîne extraite. Par exemple, substring(0,2) du mot chat renverra « ch ». Le caractère 0 étant c, et le 2 étant a.

Si la clé commence par « ubuVers », elle est à nous et nous devons la traiter. La première chose que nous allons faire, c'est écrire la clé et la valeur dans la console pour le débogage, puis nous allons créer tout un tas de variables.

11

The first variable in this list is the list element that we have been writing our versions to. Next we are creating an li element to hold our ubuntu version. Still nothing new here. The third, fourth, and fifth items on the variable list are grabbing our version and release information and formatting it for our list. obj was the variable we made earlier to hold the value from our localStorage information and inside of that was was a release and a version. obj.version and obj.release is how we get that information back out. And last but certainly not least: itemDeleteButton, itemDeleteButtonText, itemEditButton, and itemEditButtonText are creating elements and text for our new edit and delete buttons. Now we are going to jump into setting attributes and onClick functions for new buttons. Each button needs to be created per item so they can be attached to the item it will be editing/deleting. Each button is getting a new attribute with setAttribute. The attribute is ID, and is being set to its key. Then each button is getting an onclick command to interact with javascript when pressed. The delete button is running a function that will be calling a deleteItem() function with an ID being passed to it. The edit button is doing the same with a respective editItem() function.

La première variable dans cette liste est l'élément dans lequel nous écrivons nos versions. Ensuite, nous créons un élément li pour placer notre version d'Ubuntu. Toujours rien de nouveau ici. Les troisième, quatrième et cinquième éléments de la liste de variables récupèrent les informations de version et de nom et les formatent pour notre liste. obj est la variable que nous avons créée précédemment pour contenir la valeur de nos informations localStorage et à l'intérieur de laquelle se trouvent une version et son nom. obj.version et obj.release permettent de récupérer ces informations. Enfin, mais ce n'est certainement pas le moins important : itemDeleteButton, itemDeleteButtonText, itemEditButton et itemEditButtonText créent des éléments et des textes pour nos nouveaux boutons éditer et supprimer.

Maintenant, nous allons passer au réglage des attributs et aux fonctions onClick des nouveaux boutons. Chaque bouton doit être créé par élément afin qu'il puisse être rattaché à l'élément qu'il va modifier/supprimer. Chaque bouton récupère un nouvel attribut avec setAttribute. L'attribut est ID ; il est réglé à la valeur de sa clé. Ensuite, chaque bouton a une commande onclick pour interagir avec javascript lorsque l'on appuie dessus. Le bouton de suppression exécute une fonction appelée deleteItem() qui prend en attribut un ID. Le bouton Modifier fait pareil avec une fonction équivalente editItem().

12

listItem.innerHTML and the respective edit and delete buttons are setting up the elements’ HTML between the tags. In this case it is just text, but could be full out HTML if you wanted it to be. Which finally brings us to listItem.appendChild() commands. These commands are adding the edit button to the list item, then delete, and finally adding and displaying the list item in our list. The next function we have now (shown above) is a deleteItem function that we used on our delete button. This function is fairly straightforward. The first thing we want to do is confirm that the user would like to really delete this item, so we ask them with a window.confirm() prompt. This prompt gives a cancel or ok option. If OK is pressed, it will come back into your JS as true; if cancel, it will come back as false. So if (true) { do this } else { nothing here }. If they do in fact want to delete the item, we simply pass the key that was supplied to the function into localStorage.removeItem(); and it is gone. We then let the user know it was successfully deleted and we refresh our list.

listItem.innerHTML et les boutons respectifs d'édition et de suppression mettent en place le code HTML des éléments entre les balises. Dans ce cas, c'est juste du texte, mais cela pourrait être du HTML si vous le vouliez. Ce qui nous amène finalement aux commandes listItem.appendChild(). Ces commandes ajoutent le bouton d'édition à la liste, puis celui de suppression et enfin ajoutent et affichent l'élément dans notre liste.

La fonction suivante (ci-dessus) est une fonction deleteItem que nous utilisons sur notre bouton de suppression. Cette fonction est assez simple.

La première chose que nous faisons est de confirmer que l'utilisateur souhaite vraiment supprimer cet élément, en le lui demandant avec une invite window.confirm(). Ce message propose une option d'annulation ou OK. Si vous appuyez sur OK, il va revenir dans votre JS avec la valeur vrai ; si vous annulez, il reviendra avec faux. Donc, si (vrai) {faire ceci} sinon {ne rien faire}. Si l'utilisateur veut vraiment supprimer l'élément, nous passons simplement la clé qui a été fournie à la fonction à localStorage.removeItem() et il n'existe plus. Nous confirmons alors à l'utilisateur qu'il a été supprimé avec succès et nous rafraîchissons notre liste.

13

The editItem function (shown below) is almost as simple. As I mentioned earlier a couple times in other functions, we already set those up for editing. Here is the goodness that makes all that work. In this case, we are grabbing the information from localStorage based on the key that was passed to the function, just like we did for each of the rows in localStorage when we were displaying them. Instead of displaying them, though, we are setting the value for the form fields to the information we get back. After the fields are repopulated with the information, we set the submit button to display “Edit Version” instead of “Add”, and tie a key to its object with the value of the key we are editing. That way, when they press the submit button, it is doing the same thing it normally would, only this time it will trip our submit.key exists if statement in our storeData function and be set to the value of the key object in our submit button object. Pretty cool, eh?

La fonction editItem (ci-dessous) est presque aussi simple. Comme je l'ai dit plus tôt à quelques reprises dans d'autres fonctions, nous avons déjà mis en place ce qu'il faut pour l'édition. Ici, nous faisons juste le travail.

Dans ce cas, nous récupérons les informations de localStorage à partir de la clé qui a été passée à la fonction, tout comme nous l'avons fait pour chacune des lignes dans localStorage lorsque nous les affichions. Au lieu de les afficher, cette fois-ci nous réglons la valeur pour les champs de formulaire à l'information que nous avons récupérée.

Après que les champs soient remplis avec les informations, nous réglons le bouton submit pour afficher « Modifier la version » au lieu de « Ajouter », et attachons une clé à son objet avec la valeur de la clé que nous éditons. De cette façon, quand on appuie sur le bouton envoi, il fait la même chose qu'il ferait normalement, mais cette fois-ci, il déclenchera notre instruction « if submit.key exists » dans notre fonction storeData et sera réglé à la valeur de l'objet clé de notre bouton. Plutôt cool, hein ?

14

Our last function is a very, very easy function. However, it has been elaborated and filled up with a lot of extra lines it doesn’t need, just to make sure the user actually wants to do it. It is the clear local storage button function: http://pastebin.com/i9shwb7z The only line we really need in this whole function is localStorage.clear(). However, when this is run, it will clear everything in it, no going back. With that said, the first thing you are going to want to do, is make sure that there is anything in there in the first place and let the user know if there isn’t. If there is, and it will be removing data from it, ask the user if he/she really wants to do this. The importance here is that localStorage can contain information from your site, and from others. It isn’t like a cookie that can be accessed only by your domain name – localStorage can be read and manipulated by any site, any domain, any page. If they do indeed want to delete, remove it and call our displayData() function to display nothing in our list.

Notre dernière fonction est une fonction très, très facile. Cependant, elle a été élaborée et remplie avec beaucoup de lignes supplémentaires dont elle n'a pas besoin, juste pour s'assurer que l'utilisateur veut réellement le faire. C'est la fonction pour vider le stockage local : http://pastebin.com/i9shwb7z

La seule ligne dont nous avons vraiment besoin dans cette fonction est localStorage.clear(). Toutefois, lorsqu'elle est exécutée, cela efface tout ce qu'il contient et pas question d'annuler. Celà étant dit, la première chose que vous allez vouloir faire, c'est de vous assurer qu'il y a quelque chose là-dedans au départ, et d'informer l'utilisateur si ce n'est pas le cas. S'il y a des choses et qu'il va supprimer les données qu'il contient, demandez à l'utilisateur s'il/elle veut vraiment le faire. L'important ici est que localStorage peut contenir des informations provenant de votre site et d'autres aussi. Ce n'est pas comme un cookie qui peut être consulté seulement par votre nom de domaine - localStorage peut être lu et manipulé par n'importe quel site, n'importe quel domaine, n'importe quelle page. S'il veut vraiment l'effacer, on le supprime et on appelle notre fonction displayData() pour ne rien afficher dans notre liste.

15

Now that we are done with all of our functions, it is time to tell the browser what to do when it loads our javascript: http://pastebin.com/VqzFiDYF The first thing is a variable for our form. Next, we are attaching the processForm function to our form when a user submits it. To end our javascript goodness for the month, we are calling the displayData() function so that when a user comes to our page, it will pull up any information he previously entered into our form when it loads. I very much hope you enjoyed this month’s article. I am planning on showing you how to convert your code to JQuery, add a little bit of “zaz” to our page, and moving our localStorage to a real database. I would love to hear your suggestions for any future web developer articles you would like to see. Feel free to shoot over your suggestions or any other comments via twitter: @aliendev2. Remember to check back next month for some more web developer awesomeness. You can also check out, follow, fork, download, view revisions of the code on github: https://github.com/aliendev/FCM-UbuntuVers.

Maintenant que nous avons fini avec toutes nos fonctions, le moment est venu de dire au navigateur ce qu'il doit faire quand il charge notre javascript : http://pastebin.com/VqzFiDYF

La première chose est une variable pour notre formulaire. Ensuite, nous attachons la fonction processForm à notre formulaire lorsqu'un utilisateur le valide. Pour terminer sur javascript cette fois-ci, nous appelons la fonction displayData() de sorte que quand un utilisateur vient sur notre page, cela affichera toutes les informations qu'il avait déjà saisies dans notre formulaire dès son chargement.

J'espère de tout cœur que vous avez apprécié l'article de ce mois-ci. J'ai l'intention de vous montrer comment convertir votre code en JQuery, ajouter un peu de « peps » sur notre page, et déplacer notre localStorage vers une véritable base de données. J'aimerais entendre vos suggestions pour de futurs articles de développeur web que vous souhaiteriez lire. N'hésitez pas à envoyer vos suggestions ou tout autre commentaire via Twitter : @aliendev2.

N'oubliez pas de revenir le mois prochain pour encore plus de lumière sur le développement web. Vous pouvez également récupérer, suivre, améliorer, télécharger, visualiser les révisions du code sur github : https://github.com/aliendev/FCM-UbuntuVers.

issue70/developpement_web_-_crud.txt · Dernière modification : 2013/05/23 15:50 de auntiee