prez-js



prez-js

0 0


prez-js

Javascript concepts and notions prezentation.

On Github pierr / prez-js

JavaScript

new features

by Pierre Besson

Overview

  • Ajax
  • WebSockets
  • WebWorkers
  • Geolocalization
  • File Api
  • Offline
  • Classic Patterns
  • Promise

Communication

XMLHttpRequest

var req = new XMLHttpRequest();
req.open('GET', 'http://www.mozilla.org/', true);
req.onreadystatechange = function (aEvt) {
  if (req.readyState == 4) {
     if(req.status == 200)
      dump(req.responseText);
     else
      dump("Erreur pendant le chargement de la page.\n");
  }
};
req.send(null);

WebSockets (1/3)

  • Open a communication between the client and the server.
  • The data exchange is not done with http => WS protocol => No header
  • WS can be use to have clients talking to clients
  • Example
  • MDN
  • socket.io

WebSockets server (2/3)

var io = require('socket.io').listen(80);
io.sockets.on('connection', function (socket) {

  socket.emit('news', { hello: 'world' });

  socket.on('my other event', function (data) {
    console.log(data);
  });

});

WebSockets client (3/3)

 var socket = io.connect('http://localhost');
  socket.on('news', function (data) {
    console.log(data);
    socket.emit('my other event', { my: 'data' });
  });

JS api

Web workers (1/2)

  • Background scripts inside the application
  • Run in a isaolated thread
//Create the Worker from a separate file
var worker = new Worker('doWork.js');
//Listen to the ww messages
worker.addEventListener('message', function(e) {
  console.log('Worker said: ', e.data);
}, false);
// Send data to our worker and start it.
worker.postMessage('Worker, it's time to run.);

Web workers (2/2)

What can they do

  • Access navigator, location, xhr, appcache, other worker, external scripts with importScripts()
  • No Access DOM, window, document, parent
  • Example

  • html5rocks

Geolocation (1/3)

  • Ability to get from a device its position
  • It is an asynchronous operation, a callback must be written
  • It could be unavailable on the device.
  • MDN
  • Example

Geolocation current position (2/3)

navigator.geolocation.getCurrentPosition(function(position) {
  do_something(position.coords.latitude, position.coords.longitude);
});
  • You can get the current position

Geolocation watch position(3/3)

var watchID = navigator.geolocation
                       .watchPosition(
                         geo_success, 
                         geo_error, 
                         {
                           enableHighAccuracy:true, 
                           maximumAge:30000, 
                           timeout:27000
                        });
  • You can watch the user position, a callback is called each time the position change.
  • The watch can be cancelled with navigator.geolocation.clearWatch(watchID);

File API (1/2)

  <input type="file" id="input" multiple/>
  • Add a multiple options
  • File can be accessed with JavaScript

File API (2/2)

var inputElement = document.getElementById("input");
inputElement.addEventListener("change", handleFiles, false);
function handleFiles() {
  var fileList = this.files;
  if(this.files.length === 0){return;}
  var file = files[0];
  console.log(file.name, file.type, file.lastModifiedDate);
}

Offline (1/2)

  • Application cache
  • Manifest file
    CACHE MANIFEST
    # 2012-02-21 v1.0.0
    /theme.css
    /logo.gif
    /main.js

Offline (2/2)

  • DOM storage
  • Local Storage, limit, indexDB
    //Save the item.
    localStorage.setItem(
    'papa', 
    JSON.stringify({singe: 'blue'})
    );
    //Get the item
    JSON.parse(localStorage.getItem('papa')); 
    //Object {singe: "blue"}

Promise

Callback problem

  • Answer to the callback problem which are difficult to manage when the workflow is complex.
  • If an exception occurs, the thread is broken.
  • A callback must be register before its called.
  • A callback can be trigger multiple times.

State

  • Pending: don't get a result.
  • Fullfilled: unable to get a result.
  • Rejected: a problem occurs.
  • Setteled: fullfilled or rejected

How it works

  • Must be followed by a then(onFullFilled, [,onRejected])
  • Each argument is optional and must be a function
  • Only one will be called, once
  • The call is asynchronous

The code

var promise = new Promise(function(resolve, reject) {
      //Do something maybe asynchronous or not
      var isOk = treatement();
      if (isOk) {
        resolve("It works...");
      } else {
        reject(Error("It does not work!"))
}).then(console.log, console.error);

More