Skip to content

Commit 08a3f89

Browse files
committed
Add JavaScript basic callback and promise documentation
1 parent 419969f commit 08a3f89

File tree

5 files changed

+178
-0
lines changed

5 files changed

+178
-0
lines changed

Diff for: docs/02_javascript/basic/callback-promises.md

+105
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,105 @@
1+
---
2+
3+
sidebar_position: 1
4+
tags:
5+
6+
- callbacks
7+
- promise
8+
9+
---
10+
11+
# Callbacks & Promise
12+
13+
A callback function is a function passed into another function as an argument, so a callback is a function will be executed after parent function is executed
14+
15+
## Callback
16+
17+
```jsx
18+
function func1(x) { alert(x); }
19+
// 用 func1 當作參數傳入函式 func2
20+
function func2(var1, callback) {
21+
callback(var1);
22+
}
23+
func2(2, func1);
24+
```
25+
26+
## Promise
27+
28+
The Promise object represents the eventual completion (or failure) of an asynchronous operation and allow us to work with the results.
29+
Promises have three states: `pending`, `fulfilled` or `rejected`.
30+
31+
Promises help you naturally handle errors, and write cleaner code by not having callback parameters.
32+
33+
Promise 是一個表示非同步運算的最終 完成 或 失敗 的物件。Promise 物件會有三種狀態::pending 初始狀態 、 fulfilled 表示操作成功地完成 、 rejected 表示操作失敗。如果我們需要依序串連執行多個 Promise 功能的話,可以透過 .then() 來做到。
34+
35+
![alt text](image.png)
36+
37+
```jsx
38+
var p = new Promise(function(resolve, reject) {
39+
// Do an async task and then...
40+
if(/* good condition */) {
41+
resolve('Success!');
42+
} else {
43+
reject('Failure!');
44+
}
45+
});
46+
47+
p()
48+
.then(() => {
49+
/* do something with the result */
50+
})
51+
.catch(() => {
52+
/* error */
53+
})
54+
.finally(() => {
55+
/* runs when the promise is settled,
56+
doesn't matter successfully or not
57+
他在 promise 發生後一開始就被觸發
58+
*/
59+
})
60+
```
61+
62+
Advance Exercise
63+
64+
<https://medium.com/hannah-lin/%E9%9D%A2%E8%A9%A6-%E8%80%83%E9%A9%97%E4%BD%A0%E5%B0%8D-promise-%E7%9A%84%E7%86%9F%E5%BA%A6%E4%B9%8B%E9%80%B2%E9%9A%8E%E6%87%89%E7%94%A8%E9%A1%8C-6eda0dd0d767>
65+
66+
### 延伸考題 What’s about async?
67+
68+
![alt text](image-1.png)
69+
70+
The async function is syntactic sugar for promise.
71+
72+
async/await 其實是 promise 語法糖,讓你可以用更簡潔的方法達到非同步。(async function 本身就會回傳 promise)
73+
74+
用比較實務去 fetch API 就會如以下 (react Hook 為範例)
75+
76+
```jsx
77+
const [lists, setLists] = useState([])
78+
useEffect(() => {
79+
getPosts()
80+
},[])
81+
82+
83+
// promise
84+
const getPosts = () => {
85+
fetch(`https://jsonplaceholder.typicode.com/posts`)
86+
.then( res => res.json())
87+
.then(json => {
88+
setLists(json)
89+
})
90+
}
91+
92+
// asyn await
93+
const getPosts = async () => {
94+
const obj = await fetch(`https://jsonplaceholder.typicode.com/posts`)
95+
const json = await obj.json()
96+
setLists(json)
97+
}
98+
```
99+
100+
兩種寫法結果相同
101+
102+
### 推薦閱讀
103+
104+
英文: Promises, async/await (這有一系列的文章,很推薦閱讀) (<https://javascript.info/async>)
105+
中文: Promise, generator, async與ES6 (Huli 寫的這篇是我四年前學 promise 第一篇看懂的中文文章) (<https://blog.huli.tw/2015/08/26/javascript-promise-generator-async-es6/>)

Diff for: docs/02_javascript/basic/event.md

+73
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
---
2+
3+
sidebar_position: 1
4+
tags:
5+
6+
- bubbling
7+
- event-capturing
8+
9+
---
10+
11+
# Event Bubbling (propagation), Event Capturing
12+
13+
### Bubbling
14+
15+
When an event happens on an element, it first runs the handlers on it, then on its parent, then all the way up on other ancestors.
16+
17+
從啟動事件的元素節點開始,逐層往上傳遞
18+
19+
### Event Capturing
20+
21+
the event goes down to the element.
22+
從最上層的母元素開始,逐層往下傳遞
23+
24+
### Comparison
25+
26+
![alt text](image-2.png)
27+
28+
事件兩者都會執行 ,會先執行 Capturing 再執行 Bubbling
29+
30+
當然你可以提供 addEventListener 第二個參數去補抓順序
31+
32+
If it’s false (default), 會被設定為 `Bubbling`
33+
34+
If it’s true, 會被設定為 `Capturing`
35+
36+
```jsx
37+
var btn = document.getElementById('btn');
38+
btn.addEventListener('click', function(){
39+
console.log('HELLO');
40+
}, false ); // Bubbling
41+
```
42+
43+
若需要取消 Bubbling 也可以使用 event.stopPropagation()
44+
45+
### 延伸考題: What’s Event Delegation?
46+
47+
If there are many elements inside one parent, and you want to handle events on them — don’t bind handlers to each element. Instead, bind the single handler to their parent and get the child from e.target
48+
49+
Event Delegation是一種運用 Event Bubbling 概念而能減少監聽器數目的方法,將事件處理器綁在目標元素的父元素上進行處理,可以減少大量子事件監聽器的數量
50+
51+
```jsx
52+
// Before using delegated event
53+
let elements = document.querySelectorAll('ul > li > a');
54+
for (let elem of elements) {
55+
elem.addEventListener('click', function(e){
56+
console.log(e.target)
57+
// to something
58+
})
59+
}
60+
61+
// Attach a delegated event handler
62+
document.getElementById('list').addEventListener('click', function(e){
63+
if (e.target.tagName == 'a'){
64+
console.log(e.target)
65+
// to something
66+
}
67+
}
68+
```
69+
70+
### 推薦閱讀
71+
72+
英文: Bubbling and capturing, Event delegation: <https://javascript.info/bubbling-and-capturing>, <https://javascript.info/event-delegation>
73+
中文: 重新認識 JavaScript: Day 14 事件機制的原理 、Huli 的 DOM 的事件傳遞機制:捕獲與冒泡 : <https://blog.huli.tw/2017/08/27/dom-event-capture-and-propagation/>

Diff for: docs/02_javascript/basic/image-1.png

260 KB
Loading

Diff for: docs/02_javascript/basic/image-2.png

139 KB
Loading

Diff for: docs/02_javascript/basic/image.png

83.4 KB
Loading

0 commit comments

Comments
 (0)