Affichage des articles dont le libellé est class. Afficher tous les articles
Affichage des articles dont le libellé est class. Afficher tous les articles

Easy get and set

class Counter{
  
  constructor(){
    this.counterValue = 0;
  }
  
  get counter() {
    return this.counterValue;
  }
  
  set counter(val){
    this.counterValue = val;    
  }
}

let c = new Counter();

console.log(c.counter);
c.counter = 4;
console.log(c.counter);


code

Animation : class

Pour obtenir un temps écoulé :

let startTime = new Date().getTime();
function main() {

 //pour avoir un temps de simu depuis le départ
   let currTime = new Date().getTime(),
       dt = ((currTime - startTime)/1000);
       
  update(dt);
  render();

  requestId = window.requestAnimationFrame(main);
}

temps quasi constant


function main() {

  let now = Date.now(),
    dt = (now - lastTime) / 1000.0;
       
  update(dt);
  render();
  lastTime = now;
  requestId = window.requestAnimationFrame(main);

}

on pourra écrire la classe suivante :

class Oxilo extends AnimatedBloc {

  constructor(elt, { speed }) {
    
    super(elt, {
      speed
    });
  }

  static construct(elt, { speed = 1 } = {}) {
    return new Oxilo(elt, { speed });
  }

  update(dt) {   
   this.x = Math.cos(2*Math.PI*(dt))*50;
   this.y = Math.sin(Math.PI*(dt))*50;
  }

}


animation : class

Élément de base

class AnimatedBloc {

  constructor(elt, {speed = 1} = {} ) {

    this.elt = elt;

    // initial CSS
    this.initPosition( speed );
  }

  initPosition( speed ) {

    if (this.elt) {
      const {
        left,
        top
      } = this.elt.getBoundingClientRect();

      // CSS
      this.cssX = left;
      this.cssY = top;

      this.x = 0;
      this.y = 0;
      
      this.speed = speed;
    }
  }

  render() {
    this.elt.style.cssText = `left:${this.x+this.cssX}px`;
    //ctx.drawImage(Resources.get(this.sprite), this.x, this.y);
  }
  
  update() {
    this.x = this.x + this.speed;
  }

}

Héritage

class BouncingBloc extends AnimatedBloc {

  constructor(elt, {speed = 3, at = 300 } = {} ) {
    super(elt, {speed});

    this.boundary = at;
  }


  update() {
    
    super.update();

    if (this.x >= this.boundary || this.x == 0) {
      this.speed *= -1;
      this.elt.classList.toggle("bouncing");
    }


  }

}

heritage : class

Passage par défault

class Player {

 constructor({
    keysMap = new Map([
      ["up", "ArrowUp"],
      ["right", "ArrowRight"],
      ["down", "ArrowDown"],
      ["left", "ArrowLeft"],
    ]),
    x = 20,
    y = 20,
    speed = 0.5,
  } = {}) {

    Object.assign(this, { touches, x, y, speed });
    ...
    this.moveX = 0;
    this.moveY = 0;
    

  }
  ...
}


https://es6console.com/jpcwjhve/

------------ Amélioration du code

Méthode static !

class Player {

  constructor( {keysMap, x, y, speed} ) {

    Object.assign(this, {
      keysMap,
      x,
      y,
      speed
    });

    this.moveX = 0;
    this.moveY = 0;

    ...

  }
  static create({
    keysMap = new Map([
      ["ArrowUp", "up"],
      ["ArrowRight", "right"],
      ["ArrowDown", "down"],
      ["ArrowLeft", "left"],
    ]),
    x = 100,
    y = 100,
    speed = 0.5,
  } = {}) {

    return new Player({keysMap, x, y, speed})

  }
...
}

appel

Player.create();

Player.create({
    keysMap: new Map([
      ["z", "up"],
      ["d", "right"],
      ["x", "down"],
      ["q", "left"],
    ]),
    speed: 2
  });
  
https://es6console.com/jpdtv6zx/

Getter et Setter d'une classe

La syntaxe set permet de lier une propriété d'un objet à une fonction qui sera appelée à chaque tentative de modification de cette propriété.

Exemple : 

class CodeSecret {

  constructor(num) {
    // invokes the setter
    this.code = num;

  }

  set code(num) {
   
    if ( !/^ISBN/.test(num)) {
      console.log("votre code doit commencer par ISBN");
      return;
    }
    this._code = num;

  }


  get code() {
    return this._code;
  }

}

let t = new CodeSecret("dD1");

https://es6console.com/jpbn7x38/


class : Action



class Prefix {


     constructor(pref) { // pas de fx arrow

          this.pref= pref;
     }

    addPref(tab) {

      return tab.map( ( {genre,nom} ) => {
       
        let pref = genre =='m' ? `${this.pref}` : `${this.pref}e`;
       
        return `${pref} ${this.upper(nom)}`
      })
    }

    upper(s){
       return s[0].toUpperCase() + s.slice(1);
    }
}

pers =  [
{nom: "Dupont",ville: "evry",genre: "f"},
{nom: "Brusel",ville: "belfort",genre: "m"}

];
let t = new Prefix("Cher");

console.log(t.addPref(pers));


Class en action


HTML : 

<article class="td">
   <section> ...</section>
   <section> ... </section>
</article>


CSS



.hide {
   overflow : hidden;
   opacity:0;
   max-height : 0px;
   transition:all 2s ease;
   padding : 10px;
}

article>section+section {
   max-height : 300px;
   overflow : hidden;
   opacity:1;
   background-color : black;
   color : white;
   padding : 10px;
   transition:all 2s ease;
}

JS

class tdHandler {

     constructor(el) { // el = article
          this.el= el;
     }

    init() {
      this.el.addEventListener("click", () => this.action(), false);
      return this;
     }
    
    action( ) {
       this.el.lastElementChild.classList.toggle('hide');
       return this;
    } 
};

Array.from(document.querySelectorAll('.td'), (el) =>{
  let h = new tdHandler(el).init().action();
});

test fonction fléchée (pas de fonction flechée dans class)

En action


Nous allons étudier différents codes ! Coller les différentes version de js




HTML

<img src="http://www.exisoftware.com/thumbnail_generator/sample-galleries/basic-web-photo-gallery/thumbs/tn_IMG_0001.jpg" data-larger="http://www.exisoftware.com/thumbnail_generator/sample-galleries/basic-web-photo-gallery/images/IMG_0001.JPG"

alt="jolie" />


CSS


body, html
{
width: 100%; height: 100%;
  overflow : hidden;
}

img{
   padding: 10px;
   width : 100px;
}

.overlay{
    opacity : 0.8;
    color : red;
    position: fixed;
    width: 100%;
    height: 100%;
    top: 0;
    bottom: 0px;
    left: 0px;
    right: 0px;
    padding: 0 8px;
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
    background-color: #000;
    overflow: hidden;

}
.overlayimg
{
    width: 60%;
    margin: auto;
    text-align: center;
    position: fixed;
    z-index: 3;
    top: 0;
    bottom: 0px;
    left: 0px;
    right: 0px;
    padding: 0px 10px 10px;

}

JS

class imgHandler {

     constructor(el) { // like array img
          this.el= el;
     }

     init = () => {
          for(let img of this.el) {
             img.addEventListener('click',() => this._action(img));
          }
     }

     _action = (photo) => {

            let overlay = document.createElement("div");
            overlay.setAttribute("id","overlay");
            overlay.classList.add("overlay");

            document.body.appendChild(overlay);

            let img = document.createElement("img");

            img.setAttribute("id","img");
 // el
             img.src = photo.dataset.larger;

             img.classList.add("overlayimg");

             img.addEventListener('click',this._restore);
             document.body.appendChild(img);
  
           

    }

    _restore = () => {
         console.log("stop");
         document.body.removeChild(document.getElementById("overlay"));
         document.body.removeChild(document.getElementById("img"));
    }

};


var imgs = new imgHandler(document.querySelectorAll('img'));

imgs.init();


version ES6


class imgHandler {



     constructor(el) { // array like

          this.el= el;

     }

    init = () => {

      Array.from(this.el, (img) => img.addEventListener('click',() => this._action(img))); //es6 array like
      
     }
    
    _action = (el) => {

            let overlay = document.createElement("div");
            overlay.setAttribute("id","overlay");
            overlay.classList.add("overlay");
  
            document.body.appendChild(overlay);
  
            let img = document.createElement("img");

            img.setAttribute("id","img");
  
         // console.log(el)
             img.src = el.dataset.larger;
  
             img.classList.add("overlayimg");

             img.addEventListener('click',this._restore(img));
             document.body.appendChild(img);

         
           
    }

    _restore = (photo) => {
      return function(){
         console.log("stop");
         document.body.removeChild(document.getElementById("overlay"));
         document.body.removeChild(document.getElementById("img"));
      }
    }

};


var imgs = new imgHandler(document.querySelectorAll('img'));

imgs.init();


version : For of

class imgHandler {

     constructor(el) { // like array img
          this.el= el;
     }

     init = () => {
          let self = this; // this=self=objet imgHandler
          for(let img of this.el) {
                img.addEventListener('click', () => {
                    console.log(self === this); // oui
                    self._action(img);
                })
          }
     }
 
     _action = (el) => {
     
           let overlay = document.createElement("div");
            overlay.setAttribute("id","overlay");
            overlay.classList.add("overlay");

            document.body.appendChild(overlay);

            let img = document.createElement("img");

            img.setAttribute("id","img");
 // el
             img.src = el.dataset.larger;

             img.classList.add("overlayimg");

             img.addEventListener('click',this._restore);
             document.body.appendChild(img);

    }

    _restore = () => {
         console.log("stop");
         document.body.removeChild(document.getElementById("overlay"));
         document.body.removeChild(document.getElementById("img"));
    }

};


var imgs = new imgHandler(document.querySelectorAll('img'));

imgs.init();


Autre version :



class imgHandler {



     constructor(el) { // array like

          this.el= el;

     }



    init = () => {


      Array.from(this.el, (img) => img.addEventListener('click',this._action(img))); //es6 array like
      
     }
    
    _action = (el) => {
            self = this;
            return function(){
                let overlay = document.createElement("div");
            overlay.setAttribute("id","overlay");
            overlay.classList.add("overlay");
  
            document.body.appendChild(overlay);
  
            let img = document.createElement("img");

            img.setAttribute("id","img");
  
         // console.log(el)
             img.src = el.dataset.larger;
  
             img.classList.add("overlayimg");

             img.addEventListener('click',self._restore(img));
             document.body.appendChild(img);

            }
         
           
    }

    _restore = (photo) => {
      return function(){
         console.log("stop");
         document.body.removeChild(document.getElementById("overlay"));
         document.body.removeChild(document.getElementById("img"));
      }
    }

};


var imgs = new imgHandler(document.querySelectorAll('img'));

imgs.init();

Autre version

class imgHandler {

     constructor(el) { // pas de fx arrow
          this.el= el;
     }

    init = () => {
          let self = this;
          for(let img of this.el) {
                img.addEventListener('click', function(){
                    console.log(self === this); //false
                    self._action(img);
                    //self._action(this);
//self = Object imghandler et this = img courante
                })
          }
     }
    
    _action = (el) => {
           console.log("click");
           let overlay = document.createElement("div");
            overlay.setAttribute("id","overlay");
            overlay.classList.add("overlay");
  
            document.body.appendChild(overlay);
  
            let img = document.createElement("img");

            img.setAttribute("id","img");
  
         // console.log(el)
             img.src = el.dataset.larger;
  
             img.classList.add("overlayimg");

             img.addEventListener('click',this._restore(img));
             document.body.appendChild(img);

    }

    _restore = (photo) => {
      return function(){
         console.log("stop");
         document.body.removeChild(document.getElementById("overlay"));
         document.body.removeChild(document.getElementById("img"));
      }
    }

};


var imgs = new imgHandler(document.querySelectorAll('img'));

imgs.init();


autre version : closure

class imgHandler {

     constructor(el) { // pas de fx arrow
          this.el= el;
     }

    init = () => {

      for(let i=0; i<this.el.length ; i++) {
       this.el[i].addEventListener('click',this._action(this.el[i]))
      }

      
     }
    
    _action = (el) => {
       let self = this;
       return function(){
       
           console.log( this); // img
           console.log(self); // imgHandler

           let overlay = document.createElement("div");
            overlay.setAttribute("id","overlay");
            overlay.classList.add("overlay");
  
            document.body.appendChild(overlay);
  
            let img = document.createElement("img");

            img.setAttribute("id","img");
  
         // console.log(el)
             img.src = el.dataset.larger;
  
             img.classList.add("overlayimg");

             img.addEventListener('click',self._restore(img));
             document.body.appendChild(img);

       }
           
    }

    _restore = (photo) => {
      return function(){
         console.log("stop");
         document.body.removeChild(document.getElementById("overlay"));
         document.body.removeChild(document.getElementById("img"));
      }
    }

};


var imgs = new imgHandler(document.querySelectorAll('img'));

imgs.init();


version ! 


class imgHandler {

     constructor(el) { // pas de fx arrow
          this.el= el;
     }

    init = () => {

      for(let i=0; i<this.el.length ; i++) {
       this.el[i].addEventListener('click',this._action())
      }

   
     }
 
    _action = () => {
   
       let self = this;
   
       return function(){
         
           console.log(this); // img
           console.log(self); // imgHandler
       
           let overlay = document.createElement("div");
            overlay.setAttribute("id","overlay");
            overlay.classList.add("overlay");

            document.body.appendChild(overlay);

            let img = document.createElement("img");

            img.setAttribute("id","img");

         // console.log(this)
             img.src = this.dataset.larger;

             img.classList.add("overlayimg");

             img.addEventListener('click',self._restore(img));
             document.body.appendChild(img);

       }
         
    }

    _restore = (photo) => {
      return function(){
         console.log("stop");
         document.body.removeChild(document.getElementById("overlay"));
         document.body.removeChild(document.getElementById("img"));
      }
    }

};


var imgs = new imgHandler(document.querySelectorAll('img'));

imgs.init();



Création d'un objet

class elHandler {

     constructor(el) { // pas de fx arrow
          this.el= el;
          
          this.init();
     }

    init = () => {
      this.el.addEventListener("click",
                event => this._action(event.type,this.el), false);
      return this;
     }
    
    _action = (type,el) => {
       console.log(` Handling + ${type} for ${el.id} `);
       el.classList.toggle("red");
       return this;
    }

};


let objDiv = new elHandler(document.getElementById("para1"));




Remarque :

Examiner le code pour

class elHandler { constructor(el) { // pas de fx arrow this.el= el; this.init(); } init(){ this.el.addEventListener("click", event => this._action(event.type,this.el), false); return this; } _action = (type,el) => { console.log(` Handling + ${type} for ${el.id} `); el.classList.toggle("red"); return this; } }; var objDiv = new elHandler(document.getElementById("para1")); Et finalement

class elHandler { constructor(el) { // pas de fx arrow this.el = el; this.init(); } init() { this.el.addEventListener("click", function(event) { document.body.insertAdjacentHTML('beforeend', `<div id="two">this.ed = ${this.el}</div>`); this._action(event.type, this.el) }, false); return this; } _action = (type, el) => { el.classList.toggle("red"); return this; } };