Support\Web_Cloud\WEB_Javascript_B.md
- using CamelCase convention for naming class
- first letter is UPPERCASE
// example
class Cruise {}
let firstCruise = new Cruise();
// example
class Cruise {
constructor(cruiseDate) {
this.cruiseDate = cruiseDate; // need use this keyword
}
}
let cruise2018 = new Cruise("22-DEC-2018");
console.log(cruise2018.cruiseDate);
- don't need keyword "function" when define class method
class Cruise {
constructor(cruiseDate, cruiseLine) {
this.cruiseDate = cruiseDate;
this.cruiseLine = cruiseLine;
}
greeting() {
return `I will cruise on ${this.cruiseDate} with ${this.cruiseLine}`;
}
}
let cruise2018 = new Cruise("22-DEC-2018", "NCL Bliss");
console.log(cruise2018.greeting());
// I will cruise on 22-DEC-2018 with NCL Bliss
- use extends (don't forget 's')
- using **super** to refer parent class
class Vacation {
constructor(vacationType, vacationDate) {
this.vacationType = vacationType;
this.vacationDate = vacationDate;
}
greeting() {
return `I will have a ${this.vacationType} vacation on ${
this.vacationDate
}`;
}
}
class CruiseVacation extends Vacation {
constructor(cruiseDate, cruiseLine, days) {
super("Cruise", cruiseDate);
this.cruiseLine = cruiseLine;
this.days = days;
}
greeting() {
return `${super.greeting()} with ${this.cruiseLine} for ${this.days} days`;
}
}
let cruise2018 = new CruiseVacation("22-DEC-2018", "NCL Bliss", 7);
console.log(cruise2018.greeting());
// I will have a Cruise vacation on 22-DEC-2018 with NCL Bliss for 7 days
- ES6 modules now have strict mode enabled by default (no 'use strict' is required).
// Moduel definition File: src/models/cruise.js
export class Cruise {
constructor(cruiseDate) {
this.cruiseDate = cruiseDate; // need use this keyword
}
}
// Testing file: src/test.js
import { Cruise } from "./models/cruise.js";
let cruise2018 = new Cruise("22-DEC-2018");
console.log(cruise2018.cruiseDate);
- BOM: Browser Object Model
- DOM: Document Object Model
The BOM (Browser Object Model) consists of the objects navigator, history, screen, location and document which are children of window. In the document node is the DOM (Document Object Model), the document object model, which represents the contents of the page. You can manipulate it using javascript.
- Properties
- document
- location
- console
- innerHeight
- innerWidth
- pageXOffset
- pageYOffset
- Methods
- alert()
- back()
- confirm()
- Events
- not commonly used
console.log(window.innerWidth);
console.log(window.innerHeight);
let intervalId = setInterval(function() {
console.log("2 seconds passed");
}, 2000);
// to cancel it
clearInterval(intervalId);
- Properties
- href
- hostname
- port
- protocol
- pathname
- search
- Methods
- assign()
- reload()
- Events
- not commonly used
// Example: open www.google.com and try below
console.log(location.href); // https://www.google.com/
console.log(location.hostname); // www.google.com
console.log(location.pathname); // /
console.log(location.protocol); // https:
- Properties
- body
- forms
- links
- Methods
- createElement()
- createEvent()
- getElementById()
- getElementByClassName()
- getElementByTagName()
- querySelect()
- querySelectAll()
- Events
- onload
- onclick
- onkeypress
document.getElementById("firstName");
document.getElementByClassName("cool");
document.getElementByTagName("a");
let el = document.getElementById("elementId");
el.textContext = "new text here";
el.setAttribute("name", "nameValue");
el.classList.add("myClassName");
el.classList.remove("myClassName");
el.style.color = "red";
try {
let cruise2018 = new cruise();
} catch (error) {
console.log("something went wrong: ", error);
}
console.log("let's continue executing ...");
// let's continue executing ...
try {
let cruise2018 = "new cruise()";
} catch (error) {
console.log("something went wrong: ", error);
} finally {
console.log("this will always executes");
}
try {
let salary = -1000;
if (salary < 0) {
throw new Error("Salary is negative");
}
} catch (error) {
console.log("something went wrong: ", error);
} finally {
console.log("this will always executes");
}
- function(resolve, reject)
let myPromise = new Promise(function(resolve, reject) {
setTimeout(resolve, 100, "++ promise is resolved");
});
console.log(myPromise);
- then(fullfilledFn, rejectedFn)
let myPromise1 = new Promise(function(resolve, reject) {
setTimeout(resolve, 100, "++ promise is resolved");
});
let myPromise2 = new Promise(function(resolve, reject) {
setTimeout(reject, 200, "*** promise is rejected");
});
myPromise1.then(
value => console.log("resolved: ", value),
error => console.log("rejected: ", error)
);
myPromise2.then(
value => console.log("resolved: ", value),
error => console.log("rejected: ", error)
);
// Method A: old syntax
let xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (this.readyStatus === 4 && this.status === 200) {
console.log(this.responseText);
}
};
xhr.open(
"GET",
"http://5bf87814c480680013bc7d9b.mockapi.io/api/v1/users",
true
);
xhr.send();
// Method B: preferred
// Source: BradTraversy - Udemy: ModernJSFromBeginning|Section7
document.getElementById('button').addEventListener('click', loadData);
function loadData() {
// Create an XHR Object
const xhr = new XMLHttpRequest();
// Open
xhr.open('GET', 'test.txt', true);
console.log('READYSTATE', xhr.readyState);
// Optional - Used for spinners/loaders
xhr.onprogress = function () {
console.log('READYSTATE', xhr.readyState);
}
// Method A: onload property is fairly new
// this is preferred over method A
xhr.onload = function () {
console.log('READYSTATE', xhr.readyState);
if (this.status === 200) {
document.getElementById('output').innerHTML =
`<h1>${this.responseText}</h1>`
}
}
// readyState Values
// 0: request not initialized
// 1: serer connection established
// 2: request received
// 3: processing request
// 4: request finished and response is ready
// HTTP Status
// 200: "OK"
// 403: "Forbidden"
// 404: "Not Found"
// error handling
xhr.onerror = function () {
console.log('request error ...');
}
xhr.send();
}
- let promise = $.get(url);
<!-- npm install jquery -->
import $ from "jquery";
let myPromise = $.get(
"http://5bf87814c480680013bc7d9b.mockapi.io/api/v1/users"
);
myPromise.then(
data => console.log("+++success: ", data),
error => console.log("***error: ", error)
);
- let promise = $.post(url, data)
<!-- npm install jquery -->
import $ from "jquery";
let kevin = {
name: "Kevin Zhang",
avatar: "kevin.jpg"
};
let myPromise = $.post(
"http://5bf87814c480680013bc7d9b.mockapi.io/api/v1/users",
kevin
);
myPromise.then(
data => console.log("+++success: ", data),
error => console.log("***error: ", error)
);
let myForm = document.getElementById("my-form");
myForm.addEventListener("submit", event => {
// prevent the browser from submitting the form
event.preventDefault();
});
let myForm = document.getElementById("my-form");
myForm.addEventListener("submit", event => {
let user = myForm.elements["user"];
let avatarFile = myForm.elements["avatar-file"];
console.log(user.value, avatarFile.value);
// prevent the browser from submitting the form
event.preventDefault();
});
Form Field
let myForm = document.getElementById("my-form");
myForm.addEventListener("submit", event => {
let user = myForm.elements["user"];
let userError = document.getElementById("user-error");
if (user.value.length < 4) {
userError.textContent = "Invalid Entry";
userError.style.color = "red";
userError.style.borderColor = "red";
user.focus();
// prevent the browser from submitting the form
event.preventDefault();
}
});
Instead of posting name-value-pair, somethings, we just want to post data as object literal (e.g. JSON) to the server. In below, because we are posting data ourselves (via jQuery), make sure you call preventDefault()
import $ from "jquery";
let myForm = document.getElementById("my-form");
myForm.addEventListener("submit", event => {
let user = myForm.elements["user"];
let avatarFile = myForm.elements["avatar-file"];
let postingData = {
user: user.value,
avatarFile: avatarFile.value
};
let myPromise = $.post(
"http://5bf87814c480680013bc7d9b.mockapi.io/api/v1/users",
postingData
);
myPromise.then(
data => console.log("+++success: ", data),
error => console.log("***error: ", error)
);
// prevent the browser from submitting the form
event.preventDefault();
});
Read this in more details
let inputString = "console.log('we will go cruise');";
eval(inputString); // we will go cruise
- use SSL
- use HTTP Header: Strict-Transport-Security
- Use cookie attributes: Secure and HttpOnly
- CSP: Content Security Policy
- Use HTTP Header: Content-Security-Policy
CORS: Cross Origin Resource Sharing
- Use HTTP Header: Access-Control-Allow-Origin