Outils pour utilisateurs

Outils du site


devweb:javascript (lu 42001 fois)

Javascript

Function

Définir une valeur par défaut

function update_couleur(famille,marque,matiere){
  marque  = marque  || 'all'; // valeur par défaut
  matiere = matiere || 'all'; // valeur par défaut
 
  ...
}

Function synchrone ou asynchrone

Synchronous Functions

Most functions in Javascript are synchronous. If you were to call several synchronous functions in a row

doSomething();
doSomethingElse();
doSomethingUsefulThisTime();

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

doSomething();
doSomethingElse();
doSomethingUsefulThisTime();

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

function some_3secs_function(value, callback){
  //do stuff
  callback();
}

then you can call then in order, like this:

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.
    });
  });
});

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.

setTimeout(doSomething, 10);
setTimeout(doSomethingElse, 10);
setTimeout(doSomethingUsefulThisTime, 10);

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.

function executeAsynchronously(functions, timeout) {
  for(var i = 0; i < functions.length; i++) {
    setTimeout(functions[i], timeout);
  }
}

This can be called like so:

executeAsynchronously(
    [doSomething, doSomethingElse, doSomethingUsefulThisTime], 10);

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

function update_var1(){
  updated_var1=false;
  $.ajax({...}).done(function(){
    // du code
    updated_var1=true;
  });
}

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

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);
}

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

update_all_var(function(){
  update_resultat();
});

Animation

Réécrire l'url sans recharger la page

if(history.pushState)
  history.pushState({}, '', $(this).attr("href"));

Les prototypes

URL et paramètre

https://www.creativejuiz.fr/blog/javascript/recuperer-parametres-get-url-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;
}

Avec cette fonction JavaScript, vous avez deux utilisations différentes :

var name = $_GET('name'),
    age = $_GET('age');

ou, méthode plus performante :

var $_GET = $_GET(),
    name = $_GET['name'],
    age = $_GET['age'];

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 :

var deco_var = decodeURI( $_GET( 'test' ) );
devweb/javascript.txt · Dernière modification: 30-06-2016 10:17 de edmc73