aPavaloi
πŸ”— iampava.com/cliw
{ about me }
{ about you }

πŸ‘¨β€πŸŽ“πŸ‘©β€πŸŽ“

πŸ”₯ CLIW πŸ”₯

Official Lab Page

Official Course Page

I expect from you to:

βœ… know most/all information from the TW labs
βœ… to be resourceful in find solutions on your own
βœ… know when to seek help and don't be afraid to do so

You can expect of me to:

βœ… help you outside laboratory hours
βœ… treat you fair & square

By the end of this course you:

πŸ”₯ will have the skills to build not trivial 
FE projects with a strong focus on Vanilla JavaScript
🀘 will have worked on a personal project which showcases your skills 
πŸ‘¨β€πŸ­ will be ready to venture into the real world and get into a summer job/internship*
🀝 will have worked with multiple colleagues and thus grow your team-work skills 

THIS course will not focus on:

❌ JS frameworks
❌ CSS pre-processors 
❌ accesibility
❌ build tools, deployments etc.

πŸ‘·β€β™‚οΈ

Project

πŸ“

Course Tests

πŸ“

Lab Tests

=

final grade

+

+

PROJECT

work on something you ❀

pROTOTYPE | WEEK #5 🀘

ARCHITECTURE | WEEK #11 πŸ’ͺ

fINAL SOLUTION | EXAM WEEK 🀞

TEAMS OF 2 || 3 🀝

just vanilla JS

😭

😎

OR

if you no choose,

we choose for you 😈

4 unannounced:

βœ… tests during the course
βœ… exercises during labs
... each graded with max 2.5 points
πŸ”‘ Get at least 5 for all project components and 5 for the course as well as the labs exercises to pass!

one last thing...

Student presentations

πŸ‘¨β€πŸ«πŸ‘©β€πŸ«

tools

VS Code
Git
DevDrive
OK, let's do this! πŸ”₯

Why Client-Side development anyway?

βœ… hugely better UX

βœ… opens up the Web to real-time apps

βœ… less strain on servers, thus cheaper

HTML

<img src="logo.png" alt="logo image">
<h1 data-from="wikipedia">JavaScript rocks</h1>
tag
attribute
custom attribute

Any web page looks like this...

<!DOCTYPE html>
<html>
    <head>
        <!-- -->
    </head>
    <body>
        <!-- -->
    </body>
</html>

I need a voluteer...

Implement Simon Says

πŸ’­ What's up with

semantic html anyway?

βœ… easy on you, the dev

βœ… easy on him/her the disabled user

CSS

SYNTAX

a {
  
    border-bottom: 2px solid blue;

}
selector
property
value

Where do we put it?

1. INLINE

<p style="font-weight: bold"> 
    A simple styled paragraph...
</p>

2. <style> tag

<style> 
    h1 {
        text-align: center;
    }
</style>

3. external

<!-- index.html -->

<link rel="stylesheet" href="style.css" />

<!-- style.css -->

footer {
    color: #000;
    background-color: #fff;
}

PRO & CONS to all of the above?

<img class="image round-image" id="profile" 
    src="user.jpg" />

<style>
    img {
        border: 1px solid black;
    }
    
    .round-image {
        border: 5px dotted yellow;
    }
    .image {
        border: 10px dotted red;
    }
   
    #profile {
        border: 2px solid blue;
}
</style>
  1. inline
  2. #id
  3. class
  4. Tag
πŸ’₯ !important

selectors #2

& rule

parentΒ  rule

.valentines.in-love {
    // both "valentines" & "in-love" 
    //      classes
    text-decoration: make-up;
}
.raining .human {
    /* "human" class elements inside a 
       "raining"-class element
    */
    display: hidden; 
    position: under-blanket;
}
.raining.valentines .in-love {
    color: red;
}
faculty.in-iasi.state-owned .b4 #gicu {
    display: none;
}
<style>

.red {
    color: red;
}

.blue {
    color: blue;
}

</style>

<p class="red blue"> Bob </p>
<p class="blue red"> Alice </p>

I need a volunteer...

Till next time:

βœ… finish styling "Simon Says"

βœ… deploy it to GitHub pages

βœ… make it social friendly on Facebook & Twitter

βœ… make a Twitter account & follow these awesome devs

EVENTS:

πŸ“… FII IT'ist | 13 Oct
9 Oct @TheGrape

Text

THANK'S πŸ™

CSS

Week #2

Simon Says review

❌ DOM transaction are expensive!

function colorPattern(values) {
  for (let i=0; i < values.length; i++) {
    document
      .getElementById(`button-${values[i]}`)
      .style.backgroundColor = "red";
    }
}
<button id="b1"> 1 </button>
<button id="b2"> 2 </button>
<!-- ... -->

<script>

function onClick(e) {
  let value = e.target.substrig(1);

  console.log(`Clicked the ${value } button`);
}

</script>

❌ Don't use ID's or classes for storing info

<div>
    <button id="b1" 
      onclick="click()"> 1 </button>
    
    <button id="b2" 
      onclick="click()"> 2 </button>
</div>

❌ Don't use memory with tons of event listeners!

Any   about Projects?
Bonus

Implement 🌡 just in HTML & CSS

Bonus

Implement a custom video player

βœ” Play/Pause

βœ” Track for changing position

βœ” Volume & Play speed

βœ” Custom styles

layout

πŸ†•πŸ†• Grid 
πŸ†• Flexbox
πŸ§“ Position
  • STATIC
  • RELATIVE
  • ABSOLUTE
  • FIXED
  • Sticky
πŸ§“ Position
  • BLOCK
    
  • INLINE-BLOCK
  • INLINE
    
  • πŸ§“ TABLE
  • πŸ†• FLEXBOX
  • πŸ†• GRID
🈹 Display 🈹

BOX Model

How do we name the CSS classes?

BEM: block element modifier

<body>
    <section class="question">
        <p class="question__body"> 
            Do you even bike?
        </p>
        <p class="question__answer">
            No
        </p>
        <p class="question__answer 
            question__answer--selected">
            Yes
        </p>
    </section>
</body>

πŸ”¬ DevTools

<br />

#1 Transforms

#logo {
    tranform: scale(1.1) rotate(35deg);
}
#logo {
    transform: scale(1.1) rotate(30deg);
    transform-origin: 0 0;
}

/* transform-origin: center | top left | top right | ... */

#2 TRANSITIONS

πŸ”΄

πŸ”΄

.5 sec
#logo {
  transition: transform .5s ease-in;
}

#logo:hover {
  transform: scale(1.1);
}
property
timing
function
duration

Box example

#2 Animations

πŸ”΄

πŸ”΄

A
A

πŸ”΄

A

πŸ”΄

A
#logo {
  animation: rotate 1s linear infinite;
}

@keyframes rotate {
  0% {
    transform: rotate(0deg);
  }

  50% {
    transform: rotate(180deg);
  }

  100% {
    transform: rotate(360deg)
  }
}
duration
name
timing
function
iteration count

Till next time:

βœ… cusom style a <video> element

THANK'S πŸ™

Week #3

Responsive

Design

πŸ’ͺ Flexible, grid-based layout

🍧 Media queries

🎨 images that resize

Media Queries

@media screen and (max-width: 450px) {
  /* ... */
}

images that resize

1 - Server-side solution
give me `cover.jpg`
seems like you're on mobile
sending `cover_small.jpg`
<picture>
  <source 
    srcset="image_high.jpg" 
    media="(min-width: 800px)">

  <source 
    srcset="image_low.jpg" 
    media="(min-width: 450px) and (max-width: 800px)">
  <img src="image_very_low.jpg" alt="image">
</picture>
2 - Client side solution
@media screen and (min-width: 800px) {
  .cover {
    background: url('cover_high.jpg');
  }
}

@media screen and (max-width: 800px) {
  .cover {
    background: url('cover_low.jpg');
  }
}
Bonus

βœ… Unsplash UI

βœ… lazy loading images

βœ… responsive'ness

Flex

one dimension
..or..
row
column
Flex Container
flex
items
ul {
  display: flex;
}

#1

#2

ul {
  flex-direction: row;
}

#3

ul {
  flex-wrap: wrap;
}
ul {
  flex-flow: column wrap-reverse;
}

#4

ul {
  justify-content: center;
}
ul {
  justify-content: space-between;
}
ul {
  justify-content: space-around;
}
Align along the main-axis!
ul {
  justify-content: space-evenly;
}
ul {
  align-items: center;
}
Align along the cross-axis!

#5

li {
  order: 5;
}

#6

Re'order items!
li {
  flex-grow: 0;
  flex-shrink: 1;
  flex-basis: 25%;
}

#6

Grow, shrink, basis
li {
  flex: 0 1 25%;
}
flex items
li {
  order: 5;
  flex: 0 1 25%;
}
flex container
ul {
  display: flex;
  flex-flow: row wrap;
  justify-content: center;
  align-items: flex-start;
}

The great hack! πŸ±β€πŸ’»

making a GRID system using Flexbox

GRID

two dimensions
row
column
CSS Grid Layout is the most powerful layout system available in CSS. 
No more 'row' syntax! 
Grid Container
grid
items
ul {
  display: grid;
  grid-gap: 1em;
}

#1

#1

Let's align them in a row!
.box-2
.box-3
.box-4
.box-1

#2

.box-1 {
  grid-column: 1/2;
}

.box-2 {
  grid-column: 2/3;
}

.box-3{
  grid-column: 3/4;
}

.box-4{
  grid-column: 4/5;
}
Let's align them in 2 rows!
.box-2
.box-3
.box-1
.box-4
.box-1 {
  grid-column: 1/2;
  grid-row: 1/2;
}


.box-2 {
  grid-column: 2/3;
  grid-row: 1/2;
}
.box-3{
  grid-column: 1/2;
  grid-row: 2/3;
}


.box-4{
  grid-column: 2/3;
  grid-row: 2/3;
}

#3

Let's give them sizes!

#4

ul {
  grid-template-columns: 10px 50px;
  grid-template-rows: repeat(2, 50px);
}
Another size unit!

#5

ul {
  grid-template-columns: .5fr 3fr;
  grid-template-rows: repeat(6, 1fr);
}
grid items
li {
  grid-column: 3/4;
  grid-row: 1/2;  
}
grid container
ul {
  display: grid;
  grid-gap: 1em;
  grid-tempalte-columns: repeat(4, 100px);
  grid-template-rows: 50px 50px;
}
Let's give them names! πŸ”₯
ul {
  grid-template-columns: repeat(4, 1fr);
  grid-template-rows: repeat(4, 1fr);
  grid-template-areas:
       "header header header header"
       "aside aside main main"
       "aside aside main main"
       "footer footer footer footer";
}
.header {
  grid-area: header;
}

.aside{
  grid-area: aside;
}

.main {
  grid-area: main;
}

.footer {
  grid-area: footer;
}
footer
aside
main
header

#6

Ready? Set! GO!
Explicit vs implicit grid!
ul {
  grid-template-columns: repeat(3, 20px);
  grid-template-rows: 10px 50px;
}

?

Let's make it responsive!
ul {
  grid-template-columns: 
        repeat(auto-fill, minmax(350px, 1fr));
}

#7

Till next time:

βœ… start working on the PROJECT!

THANK'S πŸ™

Week #4

Fun Fun

html & css

πŸ‘Β  FeedbackΒ  πŸ‘Ž

Let's play a game...

...about HTML & CSS!

🀝 2 teams

Phase #1 - 10 min

❓ decide on 5 HTML and/or CSS questions which you will ask the other team in phase #2

Phase #2

πŸ“„ exchange questions with the other team

πŸ€” discuss for 5 minutes the answers

πŸ” in turns, a different team member from each team answers a question. 1 point if it's correct, 0 points otherwise

❗ a member may chose to revert the question by appointing someone from the other team to answer. If they don't know, they lose 1 point. This can be done a max of 2 times per team

<BR />

Schema.org

Schema.org is a collaborative, community activity with a mission to create, maintain, and promote schemas for structured data on the Internet [...]

πŸ”¨ A practical usecase

SEO

Google Search works hard to understand the

content of a page.

Β 

You can help us by providing explicit clues about the meaning of a page to Google by including structured data on the page.

Microdata
JSON+LD

&

Microdata

An open-community HTML specification used to nest structured data within HTML content.

<div itemscope itemtype="http://schema.org/Product">
    <span itemprop="brand">ACME</span>
    <span itemprop="name">Executive Anvil</span>
    <img itemprop="image" src="anvil_executive.jpg" alt="Executive Anvil logo" />
    <span itemprop="description">Sleeker than ACME's Classic Anvil, the
        Executive Anvil is perfect for the business traveler
        looking for something to drop from a height.
    </span>
    Product #: <span itemprop="mpn">925872</span>
    <span itemprop="aggregateRating" itemscope itemtype="http://schema.org/AggregateRating">
        <span itemprop="ratingValue">4.4</span> stars, based on <span itemprop="reviewCount">89
        </span> reviews
    </span>

    <span itemprop="offers" itemscope itemtype="http://schema.org/Offer">
        Regular price: $179.99
        <meta itemprop="priceCurrency" content="USD" />
        $<span itemprop="price">119.99</span>
        (Sale ends <time itemprop="priceValidUntil" datetime="2020-11-05">
            5 November!</time>)
        Available from: <span itemprop="seller" itemscope itemtype="http://schema.org/Organization">
            <span itemprop="name">Executive Objects</span>
        </span>
        Condition:
        <link itemprop="itemCondition" href="http://schema.org/UsedCondition" />Previously owned,
        in excellent condition
        <link itemprop="availability" href="http://schema.org/InStock" />In stock! Order now!
    </span>
</div>

πŸ“¦ The itemscope attribute creates an item.

 <div itemscope></div>
<div 
    itemscope 
    itemtype="https://schema.org/Person">
</div>
<div 
    itemscope 
    itemtype="https://schema.org/Person">
    <span itemprop="name"> John Doe </span> 
</div>

πŸ‚ The itemprop attribute [...] identifies a property of that item.

πŸ”— The itemtype attribute [...] value is an unordered set of unique [...] valid absolute URLs, all of which are in the same vocabulary.

JSON+LD
<script type="application/ld+json">
  {
    "@context": "http://schema.org/",
    "@type": "Product",
    "name": "Executive Anvil",
    "image": [
      "https://example.com/photos/1x1/photo.jpg",
      "https://example.com/photos/4x3/photo.jpg",
      "https://example.com/photos/16x9/photo.jpg"
    ],
    "description": "Sleeker than ACME's Classic Anvil, the Executive Anvil is perfect for the business traveler looking for something to drop from a height.",
    "mpn": "925872",
    "brand": {
      "@type": "Thing",
      "name": "ACME"
    },
    "aggregateRating": {
      "@type": "AggregateRating",
      "ratingValue": "4.4",
      "reviewCount": "89"
    },
    "offers": {
      "@type": "Offer",
      "priceCurrency": "USD",
      "price": "119.99",
      "priceValidUntil": "2020-11-05",
      "itemCondition": "http://schema.org/UsedCondition",
      "availability": "http://schema.org/InStock",
      "seller": {
        "@type": "Organization",
        "name": "Executive Objects"
      }
    }
  }
</script>
Organization
Recipe

πŸ† SEO @CLIW πŸ†

Evaluation criteria:

βœ… Responsive prototype of the ui

βœ… valid HTML & CSS

βœ… uses a versioning system

βœ… written scholarly html report about

βœ” important ideas/concepts regarding overall design

βœ” user interaction methods

βœ” ways of using the management system

πŸ”— In depth

THANK'S πŸ™

Week #6

JAVASCRIPT!

But first, feedback results!

And one last thing...

The Very Basics

βœ… it's single threaded
βœ… it's a dynamic language 
βœ… it's an open language, actively developed by TC39
βœ… everything in the same global scope
βœ… naming convention is usually camelCase
βœ… officially called EcmaScript, that's why version are called ES5, ES6, etc...

== πŸ†š ===

!= πŸ†š !==

Objects

// Object creation
let myBake = {
  mark: "unknown",
  year: 2015,
  boughtFrom: {
    name: "Decathlon",
    address: "Era Shopping Park"
  }
}  
// Get properties
console.log(myBike.boughtAt.name);
console.log(myBike["boughtAt"]["name"]);

// Add properties
myBike.suspension = "full";

Arrays

// Object creation
let veryRandomList = [
    2, null, undefined, "bob", 
    [1, 2, 3] 
];

console.log(veryRandomList[3]);
// Arrays are Objects too
veryRandomList.name = "My List";

console.log(veryRandomList);

Functions

function study(subject, until = "20:00") {
  console.log(`Studying ${subject} until ${until}`;
}
// I prefer to put running code first...
button.addEventListener("click", study);

// and functions last.

βœ” can be named or anonymous

βœ” doesn't brake if missing params. It's a dynamic lang πŸ˜…

βœ” if no explicit return, it implicitly returns undefined

βœ” are first class citizens - whatever you can do with the other variables you can do with functions

  • returned from functions
  • passed to functions as arguments
  • stored in variables

SCOPE

❗ Where can we access the declared variables?

SCOPE

Function scope
⭐ access inside same-scope


⭐ access from inner scope to outer scope

SCOPE

let πŸ₯Š var

block scope   vs  function scope
function goOut() {
    if (weather === "sunny") {
        let outfit = "light & casual";
    } else {
        let outfit = "light & casual + umbrella";
    }
    
    console.log(outfit);
}
Block scope

SCOPE

let || var πŸ₯Š const

function goOut() {
    const outfit;
    if (weather === "sunny") {
        outfit = "light & casual";
    } else {
        outfit = "light & casual + umbrella";
    }
    
    console.log(outfit);
}
Error
Error
const cannot be reassigned
const person = {
    name: 'Bob',
    occupation: 'JavaScriptER',
    umbrella: true
};

if (weather === 'sunny') {
    person.umbrella = false;
}
βœ”

Let's put it all together...

function startGame() {
    const name = "Game";

    function baz() {
        var x = 2;
        if(x ===2) {
          let x = 3;
          console.log(x);
        }

        {
           // creating a block 
           const x = 33;
        }
    }
}

Debugging

is your

best friend ❀

startGame();

function startGame() {
    let players = [{
        name: "Alice",
        gold: 120,
        life: .75
    }, {
        name: "Bob"
        life: 1
    }];

    for(let i = 0; i< players.length; i++) {
      console.log(getChangeToWin(players[i]));
    }
}

function getChangeToWin(player) {
    return player.gold ** 2 * player.life;
}

<br/>

πŸ”— devdrive.io

CLOSURES

⭐ The ability of a function to access lexical scope variables even when it is executed in a different context.
function simpleF(x) {
  return function() {
    return x;
  }
}

let get11 = simpleF(11);
console.log(get11);

prototype

The prototype represents the collection of properties and methods that all instances of a certain type/class inherit.
All Array's have a sort function already defined by the language. 

We say that the sort function is on the 
 Array prototype.

prototype

⭐ We can add properties/methods to the prototype...

⭐ And even delete them...

DEMO

{
}

Constructor pattern

let myBike = new Bike("Buburuza");
myBike.ride();


function Bike() {
  this.name = name;
}

Bike.prototype.ride = function() {
  console.log(`I'm riding ${this.name} bike`);
}

ES5

class pattern

let myBike = new Bike("Buburuza");
myBike.ride();


class Bike {
  constructor(name) {
    this.name = name;
  }

  ride() {
    console.log(`I'm riding ${this.name} bike`);
  }
}

ES5

inheritance

class SuperBike extends Bike{
  constructor(name, power) {
    super(name);

    this.power = power;
  }

  getPower() {
    console.log(`My power is ${this.power}`);
  }
}

ES5

Problem...?

That's right, private is messy... Here's how we create private methods and make sure name is not changable.

class Bike {
  constructor(name) {
    this.getName = () => name;

    function privateF() {
        // ...
    }
  }

  ride() {
    console.log(`I'm riding ${this.getName()} bike`);
  }
}

πŸ₯Š player v player πŸ₯Š

Till next time:

βœ… finish the Practice-OOP exercise & send it to me for feedback & bonus points

THANK'S πŸ™

Week #7

ASYNC & DOM!

Classes & Closures

module pattern

❗ The only way to achieve public and private methods in JS
πŸŽ‰ by using CLOSURES, of course!
function MathModule() {

}
(function MathModuleIIFE() {

}());
window.PI = (function MathModuleIIFE() {
    return 3.14;
}());

console.log(PI);
window.MathM = (function MathModuleIIFE() {
    const PI = 3.141231231231;

    return {
      powPI: function powPI(x) {
        return x ** PI;
      },
      getPI: function getPI() {
        return PI;
      }
    }
}());

MathM.powPI(2); // ...
This is what many libraries out there are doing...
❗ But, how do I access the public API from my module?
😎 revealing module pattern to the rescue!
window.MathM = (function MathModuleIIFE() {
    const PI = 3.141231231231;

    return {
      powPI,
      getPI
    }

    function powPI(x) {
      return x ** PI;
    }

    function getPI() {
      return PI;
    }
}());

MathM.powPI(2); // ...
now we can access the public methods from inside the Pet

}

Using the module pattern is generally not recommended for class/instance usecases.


For those use the contructor/class pattern!

BUT...

AsynchronousΒ  = !Synchronous

for (let i = 0; i < 10; i++ ) {
    console.log(`Iteration number ${i}`);
}

console.log('Chuck Norris is a badass');







console.log('Wait, what?');
setTimeout(function textBob() {
    console.log('On my way!');
}, 2000); 
document
    .getElementById('logo')
    .addEventListener('click', textBob);

function textBob() {
    console.log("On my way!");
}
A callback is a function invoked from another function which received it as a parameter.
setTimeout(textBob, 500);


document
    .getElementById("logo")
    .addEventEventListener("click", textBob);
callback
callback

Let's practice!

Callbacks enable decoupling

Game engine

Hero Class

life decreases every second
interested 
class Hero(name, onUpdate) {
    constructor() {

      setInterval(() => {
        // do stuff
        onUpdate(data);
      }

    }
}
let GameEngine = (function (){
  let newHero = new Hero(
        "Bob", 
        onHeroUpdate
    );

  function onHeroUpdate(data) {
      // do stuff
  }
}());

But can lead to callback hell πŸ‘Ώ

fs.readdir(source, function (err, files) {
  if (err) {
    console.log('Error finding files: ' + err)
  } else {
    files.forEach(function (filename, fileIndex) {
      console.log(filename)
      gm(source + filename).size(function (err, values) {
        if (err) {
          console.log('Error identifying file size: ' + err)
        } else {
          console.log(filename + ' : ' + values)
          aspect = (values.width / values.height)
          widths.forEach(function (width, widthIndex) {
            height = Math.round(width / aspect)
            console.log('resizing ' + filename + 'to ' + height + 'x' + height)
            this.resize(width, height).write(dest + 'w' + width + '_' + filename, function(err) {
              if (err) console.log('Error writing file: ' + err)
            })
          }.bind(this))
        }
      })
    })
  }
})
We're usually using callbacks with DOM events so... regarding that

<BR/>

πŸ”₯ Promises πŸ”₯

food example
A Promise is an object representing the eventual completion or failure of an asynchronous operation. - MDN
let goodPromise = Promise.resolve("hello");
goodPromise.then(
    (resp) => console.log(resp)
);
let badPromise = Promise.reject("nay");
badPromise.then(
    (resp) => {},
    (err) => console.error(err)
);
let after5Seconds= new Promise((resolve, reject) => {
   setTimeout(() => {
        resolve(Date.now());
    }, 5000);
});

after5Seconds.then(
    resp => console.log(`The time is ${resp}`),
    err  => console.error(err)
);

Promise chaining

Promise.prototype.then  and Promise.prototype.catch return a promise.
Promise.resolve(2)
    .then(x => x + 2)
    .then(y => y * 2)
    .then(z => z * 10)
    .then(final => console.log(final));
getUsers()
    .then(users => users.filter(/* ... */))
    .then(users => users.map(/* ... */));
getUser("bob")
    .then(user => getResults(user, "js-test")
    .then(results => results.filter(r => r.total > 50))
    .then(/* ... */);

err handling

action1().then(resp1 => {
  action2(resp1).then(resp2 => {
    action3(resp2).then(resp3 => {
      console.log(resp3);
    }, err3 => {/* ... */})
  }, err2 => {/* ... */}
}, err => {/* ... */}
there's gotta 
be a better way!
action1()
    .then(resp1 => action2(resp1))
    .then(resp2 => action3(resp2))
    .then(resp3 => console.log(resp3))
    .catch(err => console.log("Error above"));

or...

action1()
    .then(resp1 => action2(resp1))
    .then(resp2 => action3(resp2))
    .catch(err => {
        console.log("Error at 1 or 2");
        return fallbackObj;
    })
    .then(resp3 => console.log(resp3))
    .catch(err => console.log("Error at 3"));

Let's practice!

fetch

the modern way of doing ajax requests ❀
fetch(url, options);
fetch("url")
    .then(resp => console.log(resp));
fetch("url")
    .then(resp => resp.json())
    .then(jsonResp => console.log(jsonResp));
fetch("url")
    .then(resp => resp.text())
    .then(textResp=> console.log(textResp));

Let's practice!

πŸ‘Š Chuck Norris API πŸ‘Š

THANK'S πŸ™

Week #10

SVG & CAnvas

+ a little async

#1 Fetch

When users navigate to a video, you need to:

1) check for permissions
2) get the actual video data

#2 svg

Scalable Vector (math drawn) Graphics!

What?

  • crisp and responsive on any display!
    
  • easy to animate
    
  • easy to make accessible
<svg width="200" height="250" version="1.1" xmlns="http://www.w3.org/2000/svg">

  <rect x="10" y="10" width="30" height="30" stroke="black" fill="transparent" stroke-width="5"/>

  <circle cx="25" cy="75" r="20" stroke="red" fill="transparent" stroke-width="5"/>
  <ellipse cx="75" cy="75" rx="20" ry="5" stroke="red" fill="transparent" stroke-width="5"/>

  <line x1="10" x2="50" y1="110" y2="150" stroke="orange" stroke-width="5"/>
  <polyline points="60 110 65 120 70 115 75 130 80 125 85 140 90 135 95 150 100 145" stroke="orange" fill="transparent" stroke-width="5"/>

  <polygon points="50 160 55 180 70 180 60 190 65 205 50 195 35 205 40 190 30 180 45 180"
      stroke="green" fill="transparent" stroke-width="5"/>

  <path d="M20,230 Q40,205 50,230 T90,230" fill="none" stroke="blue" stroke-width="5"/>
</svg>
M, m moveTo
L, l lineTo
H, h horizontal line drawn from current position
V, v vertical line drawn from current pos
Z, z joins the end of a path

Example...

Let's practice:

🎨 Animate the arms of the character!

#3 canvas

Imagine a blank Canvas on which you can programmatically paint stuff!

What?

  • geometrical shapes
  • images
  • ...or even pixel by pixel
Custom visualizations
Games 
... or maybe just Graphics!

WhY?

how?

let canvas = document.getElementById("canvas");
let ctx = canvas.getContext("2d");

ctx.beginPath();
ctx.rect(10, 100, 50, 50);

ctx.fill();

Example...

Let's practice:

🎨 Draw some mountains, a sky and a sun!

βœ… beginPath();

βœ… rect();

βœ… moveTo(); lineTo();

βœ… arc();

βœ… fill(); stroke();

Animations?

Animating stuff is like making movies!

We paint the canvas many many times a second which gives the illusion of movement.
window.requestAnimationFrame(function onFrame() {
    /* ... */
});
window.requestAnimationFrame(function onFrame() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    
    ctx.beginPath();
    ctx.rect(51, 100, 50, 50);
    ctx.fill();
});

Example...

Let's practice:

🎨 Draw and animate some birds flying across the scene!

Animations & user input?

THANK'S πŸ™

Week #11

πŸŽ…

#1 web workers

JavaScript code that runs independently (separate thread) from the browser.
  • perfect for doing intensive work in a non-blocking fashion
let myWorker =  new Worker("worker.js");

// Later...
myWorker.postMessage("Here's some data");
// worker.js

self.onmessage = function () {
    // ...
}


// OR

self.addEventListener("message", () => {
    // ...
});
But wait... There's more!

#2 Shared workers

Still a worker...but shared between windows.


Meaning, all of them have the same worker reference
  • for sharing computations/state among browser windows!

code...

// shared-worker.js

let ports = [];

self.onconnect = function (e) {
  var newPort = e.ports[0];
  self.ports.push(newPort);

  newPort.onmessage = function (e) {
    // ...
  }

  newPort.postMessage(/* ... */);
}
let myWorker =  new SharedWorker("shared-worker.js");
What? Another one?

#3 Service Worker

Still a worker...but more special 😎
  • only one per page with a very special lifecycle
  • keeps working even after closing the browser
  • can intercept & respond to requests as if they were actually coming from the server
  • can intercept push notifications
    
    
// service-worker.js

self.addEventListener('fetch', (event) => {
    if (
      event.request.destination === "image" 
      || 
      event.request.url.includes(".jpg")
      ) {
        event.respondWith(
          fetch("/chuck-norris.jpg"); // 😜
        );
    }
});
Small hack: instead of the actual images use Chuck Norris ones!

#4 Websockets

Faster, both-way communication between client & server.
  • perfect for real time apps: chats, games, stock prices, etc...
// Create WebSocket connection.
const socket = new WebSocket('url');

socket.addEventListener('open', (event) => {
    socket.send('Hello!');
});

socket.addEventListener('message', (event) => {
    console.log('Got message!', event.data);
});

THANK'S πŸ™

Week #12

Performance

Let's begin with the big question...

Are we alone in the Universe?

What happens after death?

Why should we optimize?

It's part of our duty as programmers... πŸ‘¨β€πŸ’»

HTML

CSS

JS

Fonts

images

videos

LESS is MORE!
  • Do I have useless HTML❓
  • Do I have unused CSS rules❓
  • Do I need all of that JS❓
  • Are my imagesproperly sized❓
  • Are my images formatted for performance❓
  • Am I loading any useless fonts & icons❓

...

Let's see you optimize a hell of an app... 😈

THANK'S πŸ™

Week #13

This is the end

1) Implicit binding

obj.sayHello();
let foo = {
  name: "Foo",
  sayHello: function() {
    console.log(`Hello ${this.name}`);
  }
}

let bar = {
  name: "Bar"
}
bar.sayHello = foo.sayHello;

foo.sayHello(); // ?
bar.sayHello(); // ?

2) Explicit binding

foo.call(newThis, ...)
foo.apply(newThis, [...])
let foo = {
  name: "Foo",
  sayHello: function() {
    console.log(`Hello ${this.name}`);
  }
}

let bar = { name: "Bar"}

foo.sayHello(); // ?
foo.sayHello.call(bar); // ?

2.b) Explicit binding

foo.bind(newThis)
let foo = { name: "Foo" }
let bar = { name: "Bar" }

function sayHello() {
  console.log(`Hello ${this.name}`);
}

foo.sayHello = sayHello.bind(bar);
foo.sayHello(); // ?

3) New keyword

// { }

4) Default rule

this = window*

strict mode => undefined*

function sayHello() {
  console.log(`Hello ${this.name}`};
}

sayHello();

What about priority?

  1. New keyword
  2. Explicit binding
  3. Implicit binding
  4. Default rule
Arrow functions
Do not have their own this! They `borrow` it from the enclosing scope.

Before arrow functions...

class Bike {
  constructor() {
    this.type = "Mountain bike";
  
    let self = this;

    setTimeout(function() {
      console.log(self.type);
    }, 1000);
  }
}

With arrow functions...

class Bike {
  constructor() {
    this.type = "Mountain bike";

    setTimeout(() => {
      console.log(this.type);
    }, 1000);
  }
}
Timeout & Interval
setTimeout and setInterval have their `this` bound to the window.

Practice time!

THANK'S πŸ™

CLIW | Laboratories 2018

By Pava

CLIW | Laboratories 2018

Slides for the CLIW (Client Side Web Development) laboratories I teach at the local Computer Science faculty. More info here: https://iampava.com/cliw

  • 889
Loading comments...

More from Pava