Outils pour utilisateurs

Outils du site


devweb:javascript (lu 42038 fois)

Différences

Ci-dessous, les différences entre deux révisions de la page.

Lien vers cette vue comparative

Prochaine révision
Révision précédente
devweb:javascript [09-02-2014 11:42]
edmc73 créée
devweb:javascript [30-06-2016 10:17] (Version actuelle)
edmc73
Ligne 1: Ligne 1:
 ====== Javascript ====== ====== Javascript ======
 +
 +===== Function =====
 +
 +Définir une valeur par défaut
 +<code javascript>
 +function update_couleur(famille,marque,matiere){
 +  marque  = marque  || 'all'; // valeur par défaut
 +  matiere = matiere || 'all'; // valeur par défaut
 +
 +  ...
 +}
 +</code>
 +
 +
 +===== Function synchrone ou asynchrone =====
 +
 +==== Synchronous Functions ====
 +
 +
 +Most functions in Javascript are synchronous. If you were to call several synchronous functions in a row
 +
 +<code javascript>doSomething();
 +doSomethingElse();
 +doSomethingUsefulThisTime();</code>
 +
 +they will execute in order. doSomethingElse will not start until doSomething has completed. doSomethingUsefulThisTime, in turn, will not start until doSomethingElse has completed.
 +
 +==== Asynchronous Functions ====
 +
 +Asynchronous function, however, will not wait for each other. Let us look at the same code sample we had above, this time assuming that the functions are asynchronous
 +
 +<code javascript>doSomething();
 +doSomethingElse();
 +doSomethingUsefulThisTime();</code>
 +The functions will be initialized in order, but they will all execute roughly at the same time. You can't consistently predict which one will finish first: the one that happens to take the shortest amount of time to execute will finish first.
 +
 +But sometimes, you want functions that are asynchronous to execute in order, and sometimes you want functions that are synchronous to execute asynchronously. Fortunately, this is possible with callbacks and timeouts, respectively.
 +
 +==== Callbacks ====
 +
 +Let's assume that we have three asynchronous functions that we want to execute in order, some_3secs_function, some_5secs_function, and some_8secs_function.
 +
 +Since functions can be passed as arguments in Javascript, you can pass a function as a callback to execute after the function has completed.
 +
 +If we create the functions like this
 +
 +<code javascript>function some_3secs_function(value, callback){
 +  //do stuff
 +  callback();
 +}</code>
 +then you can call then in order, like this:
 +
 +<code javascript>some_3secs_function(some_value, function() {
 +  some_5secs_function(other_value, function() {
 +    some_8secs_function(third_value, function() {
 +      //All three functions have completed, in order.
 +    });
 +  });
 +});</code>
 +
 +==== Timeouts ====
 +
 +
 +In Javascript, you can tell a function to execute after a certain timeout (in milliseconds). This can, in effect, make synchronous functions behave asynchronously.
 +
 +If we have three synchronous functions, we can execute them asynchronously using the setTimeout function.
 +
 +<code javascript>setTimeout(doSomething, 10);
 +setTimeout(doSomethingElse, 10);
 +setTimeout(doSomethingUsefulThisTime, 10);</code>
 +This is, however, a bit ugly and violates the DRY principle[wikipedia]. We could clean this up a bit by creating a function that accepts an array of functions and a timeout.
 +
 +<code javascript>function executeAsynchronously(functions, timeout) {
 +  for(var i = 0; i < functions.length; i++) {
 +    setTimeout(functions[i], timeout);
 +  }
 +}</code>
 +This can be called like so:
 +
 +<code javascript>executeAsynchronously(
 +    [doSomething, doSomethingElse, doSomethingUsefulThisTime], 10);</code>
 +In summary, if you have asynchronous functions that you want to execute syncronously, use callbacks, and if you have synchronous functions that you want to execute asynchronously, use timeouts.
 +
 +==== Exemple plus complexe ====
 +
 +Supposons 4 fonctions qui exécutent de l'ajax. On veut exécuter une 5ème fonction uniquement lorque les 4 autres auront bien reçu leur réponse ajax
 +
 +<code javascript>
 +function update_var1(){
 +  updated_var1=false;
 +  $.ajax({...}).done(function(){
 +    // du code
 +    updated_var1=true;
 +  });
 +}
 +</code>
 +Ici on sait que tant que la variable updated_var1 est false, la ré^pnse ajax n'a pas été reçu.
 +
 +Comme on a 4 fonctions, on va créer une fonction regroupant tout ça avec un callback
 +<code javascript>
 +function update_all_var(callback){
 +  update_var1();
 +  update_var2();
 +  update_var3();
 +  update_var4();
 +  
 +  var interval = setInterval(function () {
 +    if(updated_var1 && updated_var2 && updated_var3 && updated_var4){
 +      clearInterval(interval); 
 +      callback();
 +    }
 +  }, 100);
 +}</code>
 +Plutot que de faire une boucle infini qui fait généralement planter le navigateur, on utilise un setInterval qui va ici exécuter une fonction anonyme toutes les 100ms.\\
 +Si nos 4 variables updated... sont true, alors nos 4 appels ajax ont répondu, on arrête l'exécution de l'interval et on exécute la fonction callback.
 +
 +Y'a plus qu'a inclure ce code dans le main
 +<code javascript>
 +update_all_var(function(){
 +  update_resultat();
 +});
 +</code>
  
  
Ligne 6: Ligne 128:
  
   * https://github.com/matthieua/WOW Permet d'animer l'affichage d'éléments qui apparaissent lors d'un scroll   * https://github.com/matthieua/WOW Permet d'animer l'affichage d'éléments qui apparaissent lors d'un scroll
 +
 +===== Réécrire l'url sans recharger la page =====
 +
 +<code javascript>
 +if(history.pushState)
 +  history.pushState({}, '', $(this).attr("href"));
 +</code>
 +
 +===== Les prototypes =====
 +
 +http://blog.xebia.fr/2013/06/10/javascript-retour-aux-bases-constructeur-prototype-et-heritage/
 +
 +===== URL et paramètre =====
 +
 +https://www.creativejuiz.fr/blog/javascript/recuperer-parametres-get-url-javascript
 +
 +<code javascript>
 +function $_GET(param) {
 + var vars = {};
 + window.location.href.replace( location.hash, '' ).replace( 
 + /[?&]+([^=&]+)=?([^&]*)?/gi, // regexp
 + function( m, key, value ) { // callback
 + vars[key] = value !== undefined ? value : '';
 + }
 + );
 +
 + if ( param ) {
 + return vars[param] ? vars[param] : null;
 + }
 + return vars;
 +}
 +</code>
 +Avec cette fonction JavaScript, vous avez deux utilisations différentes :
 +
 +<code javascript>
 +var name = $_GET('name'),
 +    age = $_GET('age');
 +</code>
 +ou, méthode plus performante :
 +<code javascript>
 +var $_GET = $_GET(),
 +    name = $_GET['name'],
 +    age = $_GET['age'];
 +</code>
 +Bien sûr je me suis amusé à copier jusqu’au nom $_GET pour montrer que c’est possible. Mais pour des raisons de convention au sein d’un projet, notamment dans le cadre de l’utilisation de jQuery, il vous faudra certainement faire différemment. Il vous suffira alors de renommer toutes les occurences de $_GET en autre chose.
 +
 +Si jamais vous avez besoin de récupérer des valeurs complexes qui serait encodée dans l’URL (exemple avec le paramètre ?test=Hello, World!, utilisez la fonction decodeURI() ainsi :
 +
 +<code javascript>
 +var deco_var = decodeURI( $_GET( 'test' ) );
 +
 +</code>
devweb/javascript.1391942528.txt.gz · Dernière modification: 09-02-2014 11:42 de edmc73