mirror of
https://github.com/microsoft/Web-Dev-For-Beginners.git
synced 2025-08-22 14:23:06 +02:00
Merge branch 'main' into nl
This commit is contained in:
@@ -94,7 +94,7 @@ In this function, there is some interesting logic. Reading through it, can you s
|
||||
- hide the form
|
||||
- show the reset button
|
||||
|
||||
Before moving on, it's useful to learn about a very important concept available in browsers: [LocalStorage](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage). LocalStorage is a useful way to store strings in the browser as a `key-value` pair. This type of web storage can be manipulated by JavaScript to manage data in the browser. LocalStorage does not expire, while SessionStorage, another kind of web storage, is cleared when the browser is closed. The various types of storage have pros and cons to their usage.
|
||||
Before moving on, it's useful to learn about a very important concept available in browsers: [LocalStorage](https://developer.mozilla.org/docs/Web/API/Window/localStorage). LocalStorage is a useful way to store strings in the browser as a `key-value` pair. This type of web storage can be manipulated by JavaScript to manage data in the browser. LocalStorage does not expire, while SessionStorage, another kind of web storage, is cleared when the browser is closed. The various types of storage have pros and cons to their usage.
|
||||
|
||||
> Note - your browser extension has its own local storage; the main browser window is a different instance and behaves separately.
|
||||
|
||||
@@ -145,7 +145,7 @@ Before going further, we should discuss APIs. APIs, or [Application Programming
|
||||
|
||||
✅ The term 'REST' stands for 'Representational State Transfer' and features using variously-configured URLs to fetch data. Do a little research on the various types of APIs available to developers. What format appeals to you?
|
||||
|
||||
There are important things to note about this function. First notice the [`async` keyword](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function). Writing your functions so that they run asynchronously means that they wait for an action, such as data being returned, to be completed before continuing.
|
||||
There are important things to note about this function. First notice the [`async` keyword](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/async_function). Writing your functions so that they run asynchronously means that they wait for an action, such as data being returned, to be completed before continuing.
|
||||
|
||||
Here's a quick video about `async`:
|
||||
|
||||
@@ -200,7 +200,7 @@ This is a big function. What's going on here?
|
||||
- once the API responds, you assign various elements of its response data to the parts of your screen you set up to show this data.
|
||||
- if there's an error, or if there is no result, you show an error message.
|
||||
|
||||
✅ Using asyncronous programming patterns is another very useful tool in your toolbox. Read [about the various ways](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function) you can configure this type of code.
|
||||
✅ Using asyncronous programming patterns is another very useful tool in your toolbox. Read [about the various ways](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/async_function) you can configure this type of code.
|
||||
|
||||
Congratulations! If you build your extension (`npm run build`) and refresh it in your extensions pane, you have a working extension! The only thing that isn't working is the icon, and you'll fix that in the next lesson.
|
||||
|
||||
@@ -208,7 +208,7 @@ Congratulations! If you build your extension (`npm run build`) and refresh it in
|
||||
|
||||
## 🚀 Challenge
|
||||
|
||||
We've discussed several types of API so far in these lessons. Choose a web API and research in depth what it offers. For example, take a look at APIs available within browsers such as the [HTML Drag and Drop API](https://developer.mozilla.org/en-US/docs/Web/API/HTML_Drag_and_Drop_API). What makes a great API in your opinion?
|
||||
We've discussed several types of API so far in these lessons. Choose a web API and research in depth what it offers. For example, take a look at APIs available within browsers such as the [HTML Drag and Drop API](https://developer.mozilla.org/docs/Web/API/HTML_Drag_and_Drop_API). What makes a great API in your opinion?
|
||||
|
||||
## Post-Lecture Quiz
|
||||
|
||||
|
@@ -93,7 +93,7 @@ En esta función, hay una lógica interesante. Al leerlo, ¿puedes ver lo que su
|
||||
- ocultar el formulario
|
||||
- mostrar el botón de reinicio
|
||||
|
||||
Antes de continuar, es útil conocer un concepto muy importante disponible en los navegadores: [LocalStorage](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage). LocalStorage es una forma útil de almacenar cadenas en el navegador como un par "clave-valor". Este tipo de almacenamiento web puede ser manipulado por JavaScript para administrar datos en el navegador. LocalStorage no caduca, mientras que SessionStorage, otro tipo de almacenamiento web, se borra cuando se cierra el navegador. Los distintos tipos de almacenamiento tienen ventajas y desventajas para su uso.
|
||||
Antes de continuar, es útil conocer un concepto muy importante disponible en los navegadores: [LocalStorage](https://developer.mozilla.org/docs/Web/API/Window/localStorage). LocalStorage es una forma útil de almacenar cadenas en el navegador como un par "clave-valor". Este tipo de almacenamiento web puede ser manipulado por JavaScript para administrar datos en el navegador. LocalStorage no caduca, mientras que SessionStorage, otro tipo de almacenamiento web, se borra cuando se cierra el navegador. Los distintos tipos de almacenamiento tienen ventajas y desventajas para su uso.
|
||||
|
||||
> Nota: la extensión de su navegador tiene su propio almacenamiento local; la ventana principal del navegador es una instancia diferente y se comporta por separado.
|
||||
|
||||
@@ -193,13 +193,13 @@ Esta es una gran función. ¿Que está pasando aqui?
|
||||
- una vez que la API responde, asigna varios elementos de sus datos de respuesta a las partes de su pantalla que configura para mostrar estos datos.
|
||||
- si hay un error o si no hay ningún resultado, muestra un mensaje de error.
|
||||
|
||||
✅ El uso de patrones de programación asíncronos es otra herramienta muy útil en su caja de herramientas. Lea [acerca de las diversas formas](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function) puede configurar este tipo de código.
|
||||
✅ El uso de patrones de programación asíncronos es otra herramienta muy útil en su caja de herramientas. Lea [acerca de las diversas formas](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/async_function) puede configurar este tipo de código.
|
||||
|
||||
¡Felicidades! Si construye su extensión (`npm run build`) y la actualiza en su panel de extensiones, ¡tiene una extensión que funciona! Lo único que no funciona es el ícono, y lo solucionará en la próxima lección.
|
||||
|
||||
---
|
||||
|
||||
🚀 Desafío: hemos discutido varios tipos de API hasta ahora en estas lecciones. Elija una API web e investigue en profundidad lo que ofrece. Por ejemplo, eche un vistazo a las API disponibles en los navegadores, como la [API HTML de arrastrar y soltar](https://developer.mozilla.org/en-US/docs/Web/API/HTML_Drag_and_Drop_API). En tu opinión, ¿qué hace que una API sea excelente?
|
||||
🚀 Desafío: hemos discutido varios tipos de API hasta ahora en estas lecciones. Elija una API web e investigue en profundidad lo que ofrece. Por ejemplo, eche un vistazo a las API disponibles en los navegadores, como la [API HTML de arrastrar y soltar](https://developer.mozilla.org/docs/Web/API/HTML_Drag_and_Drop_API). En tu opinión, ¿qué hace que una API sea excelente?
|
||||
|
||||
|
||||
## [Post-lecture prueba](https://nice-beach-0fe9e9d0f.azurestaticapps.net/quiz/26)
|
||||
|
@@ -145,7 +145,7 @@ Prima di andare oltre, si dovrebbe parlare delle API. Le API, o [Application Pro
|
||||
|
||||
✅ Il termine "REST" sta per "Representational State Transfer" e prevede l'utilizzo di URL variamente configurati per recuperare dati. Fare una piccola ricerca sui vari tipi di API disponibili per gli sviluppatori. Quale formato piace?
|
||||
|
||||
Ci sono cose importanti da notare su questa funzione. Per prima cosa nota la [parola chiave `async`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function). Scrivere le funzioni in modo che vengano eseguite in modo asincrono significa che attendono il completamento di un'azione, come la restituzione dei dati, prima di continuare.
|
||||
Ci sono cose importanti da notare su questa funzione. Per prima cosa nota la [parola chiave `async`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/async_function). Scrivere le funzioni in modo che vengano eseguite in modo asincrono significa che attendono il completamento di un'azione, come la restituzione dei dati, prima di continuare.
|
||||
|
||||
Ecco un breve video su `async`:
|
||||
|
||||
@@ -200,7 +200,7 @@ Questa è una grande funzione. Cosa sta succedendo qui?
|
||||
- una volta che l'API risponde, si assegnano i vari elementi dei suoi dati di risposta alle parti dello schermo che sono state impostate per mostrare questi dati.
|
||||
- se c'è un errore, o se non c'è risultato, viene mostrato un messaggio di errore.
|
||||
|
||||
✅ L'utilizzo di schemi di programmazione asincrona è un altro strumento molto utile nella propria cassetta degli attrezzi. Informarsi [sui vari modi in](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function) cui si può configurare questo tipo di codice.
|
||||
✅ L'utilizzo di schemi di programmazione asincrona è un altro strumento molto utile nella propria cassetta degli attrezzi. Informarsi [sui vari modi in](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/async_function) cui si può configurare questo tipo di codice.
|
||||
|
||||
Complimenti! Se si compila la propria estensione`(npm run build`) e la si aggiorna nel pannello delle estensioni, si avrà un'estensione funzionante! L'unica cosa che non funziona è l'icona, verrà risolto nella prossima lezione.
|
||||
|
||||
@@ -208,7 +208,7 @@ Complimenti! Se si compila la propria estensione`(npm run build`) e la si aggior
|
||||
|
||||
## 🚀 Sfida
|
||||
|
||||
Finora si è discusso sui diversi tipi di API in queste lezioni. Scegliere un'API web e cercare in profondità cosa offre. Ad esempio, dare un'occhiata alle API disponibili nei browser come l' [API HTML Drag and Drop](https://developer.mozilla.org/en-US/docs/Web/API/HTML_Drag_and_Drop_API). Cosa si ritiene renda grande un'API?
|
||||
Finora si è discusso sui diversi tipi di API in queste lezioni. Scegliere un'API web e cercare in profondità cosa offre. Ad esempio, dare un'occhiata alle API disponibili nei browser come l' [API HTML Drag and Drop](https://developer.mozilla.org/docs/Web/API/HTML_Drag_and_Drop_API). Cosa si ritiene renda grande un'API?
|
||||
|
||||
## Quiz Post-Lezione
|
||||
|
||||
|
@@ -94,7 +94,7 @@ function reset(e) {
|
||||
- 폼 숨기기
|
||||
- 리셋 버튼 보이기
|
||||
|
||||
계속 진행하기 전, 브라우저에서 사용할 수 있는 매우 중요한 개념: [LocalStorage](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage)에 대해 알아 보는 것이 좋습니다. LocalStorage는 브라우저에 문자열을 `key-value` 쌍으로 저장하는 유용한 방법입니다. 이런 타입의 웹 저장소는 브라우저에서 데이터를 관리하기 위해 JavaScript로 제어할 수 있습니다. LocalStorage는 만료되지 않지만, 다른 종류의 웹 저장소인 SessionStorage는 브라우저를 닫는 즉시 지워집니다. 다양한 타입의 저장소를 사용하는 것은 장점과 단점이 존재합니다.
|
||||
계속 진행하기 전, 브라우저에서 사용할 수 있는 매우 중요한 개념: [LocalStorage](https://developer.mozilla.org/docs/Web/API/Window/localStorage)에 대해 알아 보는 것이 좋습니다. LocalStorage는 브라우저에 문자열을 `key-value` 쌍으로 저장하는 유용한 방법입니다. 이런 타입의 웹 저장소는 브라우저에서 데이터를 관리하기 위해 JavaScript로 제어할 수 있습니다. LocalStorage는 만료되지 않지만, 다른 종류의 웹 저장소인 SessionStorage는 브라우저를 닫는 즉시 지워집니다. 다양한 타입의 저장소를 사용하는 것은 장점과 단점이 존재합니다.
|
||||
|
||||
> Note - 이 브라우저 확장은 로컬 저장소를 가집니다; 주요 브라우저 창은 각자 다른 객체이며 별도로 동작합니다.
|
||||
|
||||
@@ -145,7 +145,7 @@ function setUpUser(apiKey, regionName) {
|
||||
|
||||
✅ 'REST'라는 용어는 'Representational State Transfer'를 의미하고 데이터를 가져오기 위해서 다양하게-구성된 URL을 쓰는 기능입니다. 개발자가 사용할 수 있는 다양한 타입의 API에 대해 약간 알아보십시오. 어떤 포맷이 좋습니까?
|
||||
|
||||
이 함수에 대해 유의해야 할 중요 사항이 있습니다. 먼저 [`async` keyword](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function)를 확인합니다. 비동기로 실행되도록 함수를 작성한다는 것은 수행되기 전 데이터 반환 작업이 완료될 때를 기다린다는 점을 의미합니다.
|
||||
이 함수에 대해 유의해야 할 중요 사항이 있습니다. 먼저 [`async` keyword](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/async_function)를 확인합니다. 비동기로 실행되도록 함수를 작성한다는 것은 수행되기 전 데이터 반환 작업이 완료될 때를 기다린다는 점을 의미합니다.
|
||||
|
||||
다음은 `async`에 대한 간단한 영상입니다 :
|
||||
|
||||
@@ -198,7 +198,7 @@ async function displayCarbonUsage(apiKey, region) {
|
||||
- API가 응답하면, 이 데이터를 출력하도록 설정한 화면에 응답 데이터의 다양한 요소를 할당합니다.
|
||||
- 오류가 있거나, 결과가 없는 경우에는, 오류 메시지가 출력됩니다.
|
||||
|
||||
✅ 비동기 프로그래밍 패턴을 사용하는 것은 툴박스의 다른 매우 유용한 도구입니다. [about the various ways](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function)를 읽고 이런 타입의 코드를 구성할 수 있습니다.
|
||||
✅ 비동기 프로그래밍 패턴을 사용하는 것은 툴박스의 다른 매우 유용한 도구입니다. [about the various ways](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/async_function)를 읽고 이런 타입의 코드를 구성할 수 있습니다.
|
||||
|
||||
축하합니다! 확장을 빌드하고 (`npm run build`) 확장 패널에서 새로 고치면, 작동하는 확장이 있습니다! 아이콘만 작동하지 않으며 다음 강의에서 수정할 예정입니다.
|
||||
|
||||
@@ -206,7 +206,7 @@ async function displayCarbonUsage(apiKey, region) {
|
||||
|
||||
## 🚀 도전
|
||||
|
||||
지금까지 이 강의에서 여러 타입의 API에 대해 논의했습니다. 웹 API를 선택하고 제공하는 내용에 대해 자세히 알아보세요. 예시로, [HTML Drag and Drop API](https://developer.mozilla.org/en-US/docs/Web/API/HTML_Drag_and_Drop_API)와 같은 브라우저에서 쓸 수 있는 API를 보세요. 당신의 의견에 비추어 볼 때 좋은 API를 만드는 방법은 무엇일까요?
|
||||
지금까지 이 강의에서 여러 타입의 API에 대해 논의했습니다. 웹 API를 선택하고 제공하는 내용에 대해 자세히 알아보세요. 예시로, [HTML Drag and Drop API](https://developer.mozilla.org/docs/Web/API/HTML_Drag_and_Drop_API)와 같은 브라우저에서 쓸 수 있는 API를 보세요. 당신의 의견에 비추어 볼 때 좋은 API를 만드는 방법은 무엇일까요?
|
||||
|
||||
## 강의 후 퀴즈
|
||||
|
||||
|
@@ -94,7 +94,7 @@ Dalam fungsi ini, terdapat beberapa logik yang menarik. Bacalah, anda dapat meli
|
||||
- sembunyikan borang
|
||||
- tunjukkan butang set semula
|
||||
|
||||
Sebelum meneruskan, berguna untuk mengetahui konsep yang sangat penting yang terdapat dalam penyemak imbas: [LocalStorage] https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage). LocalStorage adalah cara yang berguna untuk menyimpan rentetan dalam penyemak imbas sebagai pasangan `kunci-nilai` . Jenis storan web ini dapat dimanipulasi oleh JavaScript untuk menguruskan data di penyemak imbas. LocalStorage tidak akan habis masa berlakunya, sementara SessionStorage, jenis penyimpanan web lain, akan dihapus apabila penyemak imbas ditutup. Pelbagai jenis storan mempunyai kebaikan dan keburukan terhadap penggunaannya.
|
||||
Sebelum meneruskan, berguna untuk mengetahui konsep yang sangat penting yang terdapat dalam penyemak imbas: [LocalStorage] https://developer.mozilla.org/docs/Web/API/Window/localStorage). LocalStorage adalah cara yang berguna untuk menyimpan rentetan dalam penyemak imbas sebagai pasangan `kunci-nilai` . Jenis storan web ini dapat dimanipulasi oleh JavaScript untuk menguruskan data di penyemak imbas. LocalStorage tidak akan habis masa berlakunya, sementara SessionStorage, jenis penyimpanan web lain, akan dihapus apabila penyemak imbas ditutup. Pelbagai jenis storan mempunyai kebaikan dan keburukan terhadap penggunaannya.
|
||||
|
||||
> Catatan - pelanjutan penyemak imbas anda mempunyai storan tempatan sendiri; tetingkap penyemak imbas utama adalah contoh yang berbeza dan berkelakuan secara berasingan.
|
||||
|
||||
@@ -143,7 +143,7 @@ Sebelum melangkah lebih jauh, kita harus membincangkan API. API, atau [Applicati
|
||||
|
||||
✅ Istilah 'REST' adalah singkatan dari 'Representational State Transfer' dan ciri menggunakan URL yang dikonfigurasikan dengan pelbagai untuk mengambil data. Lakukan sedikit kajian mengenai pelbagai jenis API yang tersedia untuk pembangun. Format apa yang menarik bagi anda?
|
||||
|
||||
Terdapat perkara penting yang perlu diperhatikan mengenai fungsi ini. Perhatikan dahulu kata kunci [`async` kata kunci](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function). Menulis fungsi anda supaya mereka berjalan secara tidak segerak bermakna mereka menunggu tindakan, seperti data yang dikembalikan, diselesaikan sebelum meneruskan.
|
||||
Terdapat perkara penting yang perlu diperhatikan mengenai fungsi ini. Perhatikan dahulu kata kunci [`async` kata kunci](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/async_function). Menulis fungsi anda supaya mereka berjalan secara tidak segerak bermakna mereka menunggu tindakan, seperti data yang dikembalikan, diselesaikan sebelum meneruskan.
|
||||
|
||||
Inilah video ringkas mengenai `async`:
|
||||
|
||||
@@ -198,7 +198,7 @@ Ini adalah fungsi besar. Apa yang berlaku di sini?
|
||||
- setelah API bertindak balas, anda menetapkan pelbagai elemen data responsnya ke bahagian-bahagian skrin yang anda siapkan untuk menunjukkan data ini.
|
||||
- jika ada ralat, atau jika tidak ada hasil, anda akan menunjukkan mesej ralat.
|
||||
|
||||
✅ Menggunakan corak pengaturcaraan tak segerak adalah alat lain yang sangat berguna dalam kotak alat anda. Baca untuk[mengenai pelbagai cara](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function) anda boleh mengkonfigurasi jenis kod ini.
|
||||
✅ Menggunakan corak pengaturcaraan tak segerak adalah alat lain yang sangat berguna dalam kotak alat anda. Baca untuk[mengenai pelbagai cara](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/async_function) anda boleh mengkonfigurasi jenis kod ini.
|
||||
|
||||
Tahniah! Sekiranya anda membina pelanjutan anda (`npm run build`) dan menyegarkannya di panel pelanjutan anda, anda mempunyai sambungan yang berfungsi! Satu-satunya perkara yang tidak berfungsi ialah ikon, dan anda akan memperbaikinya pada pelajaran seterusnya.
|
||||
|
||||
@@ -206,7 +206,7 @@ Tahniah! Sekiranya anda membina pelanjutan anda (`npm run build`) dan menyegarka
|
||||
|
||||
## 🚀 Cabaran
|
||||
|
||||
Kami telah membincangkan beberapa jenis API setakat ini dalam pelajaran ini. Pilih API web dan teliti secara mendalam apa yang ditawarkannya. Sebagai contoh, perhatikan API yang tersedia dalam penyemak imbas seperti [HTML Drag and Drop API](https://developer.mozilla.org/en-US/docs/Web/API/HTML_Drag_and_Drop_API). Apa yang menjadikan API hebat pada pendapat anda?
|
||||
Kami telah membincangkan beberapa jenis API setakat ini dalam pelajaran ini. Pilih API web dan teliti secara mendalam apa yang ditawarkannya. Sebagai contoh, perhatikan API yang tersedia dalam penyemak imbas seperti [HTML Drag and Drop API](https://developer.mozilla.org/docs/Web/API/HTML_Drag_and_Drop_API). Apa yang menjadikan API hebat pada pendapat anda?
|
||||
|
||||
## Kuiz Pasca Kuliah
|
||||
|
||||
|
@@ -0,0 +1,224 @@
|
||||
# 瀏覽器擴充功能專案 Part 1:呼叫 API,使用 Local Storage
|
||||
|
||||
## 課前測驗
|
||||
|
||||
[課前測驗](https://nice-beach-0fe9e9d0f.azurestaticapps.net/quiz/25?loc=zh_tw)
|
||||
|
||||
### 大綱
|
||||
|
||||
在這堂課中,藉由傳遞你的擴充功能表單並顯示結果來呼叫 API。此外,你會了解如何儲存資料到瀏覽器的 Local Storage 中給未來使用。
|
||||
|
||||
✅ 請參考下列程式碼段,加入程式碼到檔案適當的位置
|
||||
|
||||
### 設定控制擴充功能的元素:
|
||||
|
||||
現在你有已建好的 HTML 表單與結果區 `<div>`。接下來,你需要在 `/src/index.js` 做一些處理,一點一點地構築出你的擴充功能。參考[前一堂課程](../../1-about-browsers/translations/README.zh-tw.md)來設置你的專案與了解建制過程。
|
||||
|
||||
處理 `index.js` 檔案,建立一些 `const` 變數來儲存不同用途的數值:
|
||||
|
||||
```JavaScript
|
||||
// 表單區域
|
||||
const form = document.querySelector('.form-data');
|
||||
const region = document.querySelector('.region-name');
|
||||
const apiKey = document.querySelector('.api-key');
|
||||
|
||||
// 結果區域
|
||||
const errors = document.querySelector('.errors');
|
||||
const loading = document.querySelector('.loading');
|
||||
const results = document.querySelector('.result-container');
|
||||
const usage = document.querySelector('.carbon-usage');
|
||||
const fossilfuel = document.querySelector('.fossil-fuel');
|
||||
const myregion = document.querySelector('.my-region');
|
||||
const clearBtn = document.querySelector('.clear-btn');
|
||||
```
|
||||
|
||||
這些區域會被 CSS class 給參考,它們在前一堂課中已經被你設定好了。
|
||||
|
||||
### 新增監聽者
|
||||
|
||||
接下來,新增提交與重置表單的事件監聽者與按鈕,讓使用者能提交表單或是點擊重置鈕時,事件會發生。新增初始化呼叫處理到應用中,在檔案的最下方新增:
|
||||
|
||||
```JavaScript
|
||||
form.addEventListener('submit', (e) => handleSubmit(e));
|
||||
clearBtn.addEventListener('click', (e) => reset(e));
|
||||
init();
|
||||
```
|
||||
|
||||
✅ 注意提交事件與點擊事件的寫法,事件是如何被傳入到 handleSubmit 或是 reset 函式中的。你能在不改變功能的情況下,改寫成較長的格式嗎?你比較喜歡哪一種寫法?
|
||||
|
||||
### 建立 init() 函式與 reset() 函式:
|
||||
|
||||
現在你需要建立函式 init(),處理應用程式的初始化部分:
|
||||
|
||||
```JavaScript
|
||||
function init() {
|
||||
//如果任何東西存在 localStorage 中,取出來
|
||||
const storedApiKey = localStorage.getItem('apiKey');
|
||||
const storedRegion = localStorage.getItem('regionName');
|
||||
|
||||
//設定 icon 為通用綠色
|
||||
//todo
|
||||
|
||||
if (storedApiKey === null || storedRegion === null) {
|
||||
//如果沒有 keys,顯示表單
|
||||
form.style.display = 'block';
|
||||
results.style.display = 'none';
|
||||
loading.style.display = 'none';
|
||||
clearBtn.style.display = 'none';
|
||||
errors.textContent = '';
|
||||
} else {
|
||||
//localStorage 有 saved keys/regions,顯示結果
|
||||
displayCarbonUsage(storedApiKey, storedRegion);
|
||||
results.style.display = 'none';
|
||||
form.style.display = 'none';
|
||||
clearBtn.style.display = 'block';
|
||||
}
|
||||
};
|
||||
|
||||
function reset(e) {
|
||||
e.preventDefault();
|
||||
//只清除 local storage 國家區域代碼
|
||||
localStorage.removeItem('regionName');
|
||||
init();
|
||||
}
|
||||
|
||||
```
|
||||
在函式中,有一些有趣的邏輯。閱讀它們,你看出發生什麼事嗎?
|
||||
|
||||
- 兩個 `const` 被設定為檢查用戶是否有儲存 APIKey 與國家區域代碼在 local storage 中。
|
||||
- 若兩者皆為 null,將造型設為 'block' 來顯示表單
|
||||
- 隱藏 results、loading 與 clearBtn,設定 error 文字為空字串
|
||||
- 若存在 key 與代碼,開始新的流程:
|
||||
- 呼叫 API 取得碳排放資訊
|
||||
- 隱藏結果區域
|
||||
- 隱藏表單
|
||||
- 顯示重置按鈕
|
||||
|
||||
在下一步之前,你可以學習一些瀏覽器的重要成員:[LocalStorage](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage)。 LocalStorage 是瀏覽器儲存字串的有效方法,以 `key-value` 配對兩兩一組。這種儲存型態可以被 JavaScript 管理並控制瀏覽器的資料。LocalStorage 沒有期限,而另一款網頁儲存 SessionStorage 會在瀏覽器關閉時清除內容。不同的儲存方式有各自的優缺點。
|
||||
|
||||
> 注意 ── 你的瀏覽器擴充套件有自己的 local storage。主瀏覽器視窗是不同的個體,兩者會做各自的行為。
|
||||
|
||||
你設定 APIKey 紀錄字串數值。你可以在 Edge 瀏覽器上「檢查」一個網頁 (右鍵瀏覽器來檢查),在 Applications 標籤中觀察儲存區的使用情況。
|
||||
|
||||

|
||||
|
||||
✅ 想想那些情況你不需要儲存資料到 LocalStorage 中。總體而言,將 API Keys 放在 LocalStorage 是個很糟糕的想法!你知道為什麼嗎?在我們的例子中,我們的應用程式是以教學為目的,並不會發布在應用程式商店中,所以我們選擇此中處理方式。
|
||||
|
||||
你可以發現網頁 API 能處理 LocalStorage,使用 `getItem()`、`setItem()` 或是 `removeItem()`。它們廣泛地支援不同的瀏覽器。
|
||||
|
||||
在建立函式 `init()` 中的函式 `displayCarbonUsage()` 之前,我們先建立表單提交初始化的功能。
|
||||
|
||||
### 處理表單提交
|
||||
|
||||
建立函式 `handleSubmit`,接收事件參數 `(e)`。終止網頁移轉的事件(在本例子中,我們終止瀏覽器刷新的處理)並呼叫新的函式 `setUpUser`,傳送參數 `apiKey.value` 與 `region.value`。藉由這個方式,你能將兩個初始表單的數值正確地移轉到適合的位置。
|
||||
|
||||
```JavaScript
|
||||
function handleSubmit(e) {
|
||||
e.preventDefault();
|
||||
setUpUser(apiKey.value, region.value);
|
||||
}
|
||||
```
|
||||
✅ 刷新你的記憶 ── 上堂課中的 HTML 檔案開頭有兩個輸入區域,它們的 `values` 被存到 `const` 中,並且被定為 `required`,表示瀏覽器禁止使用者輸入空值。
|
||||
|
||||
### 設定使用者
|
||||
|
||||
來到函式 `setUpUser`,這裡你能找到 apiKey 與 regionName 被存到 Local Storage 中。新增函式:
|
||||
|
||||
```JavaScript
|
||||
function setUpUser(apiKey, regionName) {
|
||||
localStorage.setItem('apiKey', apiKey);
|
||||
localStorage.setItem('regionName', regionName);
|
||||
loading.style.display = 'block';
|
||||
errors.textContent = '';
|
||||
clearBtn.style.display = 'block';
|
||||
//建立初始化呼叫
|
||||
displayCarbonUsage(apiKey, regionName);
|
||||
}
|
||||
```
|
||||
這個函式設定當 API 被呼叫時,顯示讀取訊息。到這裡,你即將建立這個擴充功能專案最重要的函式!
|
||||
|
||||
### 顯示碳排放量
|
||||
|
||||
最後,是時候查詢 API 了!
|
||||
|
||||
在前往下一步前,我們先來討論何謂 API。API,[Application Programming Interfaces](https://www.webopedia.com/TERM/A/API.html),是網頁開發者工具箱內最重要的成員。它們提供程式標準的互動模式與溝通介面,舉例來說,如果你建立一個需要存取資料庫的網頁,資料庫方可能就有人建立了 API 供你使用。API 有各式各樣的種類,最普遍使用的為[REST API](https://www.smashingmagazine.com/2018/01/understanding-using-rest-api/)。
|
||||
|
||||
✅ 'REST' 全名為 'Representational State Transfer',提供各式各樣 URL 形式來抓取資料。對網路開發者的 API 種類做一點研究,什麼形式的 API 最吸引你?
|
||||
|
||||
這條函式中有一個重要到值得紀錄的事情。第一點為[關鍵字 `async`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function)。讓你的函式非同步地執行,在行為完成前做等待,譬如資料被回傳。
|
||||
|
||||
這裡有一個簡短的影片介紹 `async`:
|
||||
|
||||
[](https://youtube.com/watch?v=YwmlRkrxvkk "Async 與 Await 處理 promises 物件")
|
||||
|
||||
> 點擊上方圖片以觀賞關於 async/await 的影片。
|
||||
|
||||
建立新的函式來詢問 C02Signal 的 API:
|
||||
|
||||
```JavaScript
|
||||
import axios from '../node_modules/axios';
|
||||
|
||||
async function displayCarbonUsage(apiKey, region) {
|
||||
try {
|
||||
await axios
|
||||
.get('https://api.co2signal.com/v1/latest', {
|
||||
params: {
|
||||
countryCode: region,
|
||||
},
|
||||
headers: {
|
||||
'auth-token': apiKey,
|
||||
},
|
||||
})
|
||||
.then((response) => {
|
||||
let CO2 = Math.floor(response.data.data.carbonIntensity);
|
||||
|
||||
//calculateColor(CO2);
|
||||
|
||||
loading.style.display = 'none';
|
||||
form.style.display = 'none';
|
||||
myregion.textContent = region;
|
||||
usage.textContent =
|
||||
Math.round(response.data.data.carbonIntensity) + ' grams (grams C02 emitted per kilowatt hour)';
|
||||
fossilfuel.textContent =
|
||||
response.data.data.fossilFuelPercentage.toFixed(2) +
|
||||
'% (percentage of fossil fuels used to generate electricity)';
|
||||
results.style.display = 'block';
|
||||
});
|
||||
} catch (error) {
|
||||
console.log(error);
|
||||
loading.style.display = 'none';
|
||||
results.style.display = 'none';
|
||||
errors.textContent = 'Sorry, we have no data for the region you have requested.';
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
這是一個挺大的函式,發生了什麼事?
|
||||
|
||||
- 遵循程式實踐過程,你使用關鍵字 `async` 讓函式非同步地作行為。函式內的 `try/catch` 區塊會在 API 回傳資料時回傳 promise 物件。因為我們無法控制 API 會多快地回應訊息(甚至無法回應訊息!),你需要處理這種不確定性的時序關係。
|
||||
- 藉由提供 API Key 訪問 co2signal API 以取得你的地區資料。要使用這把鑰匙,你必須在網頁標頭中新增認證參數。
|
||||
- 當 API 回應時,你將各種物件填入回傳的數值,並輸出到畫面上中。
|
||||
- 如果發生錯誤,或沒有結果產生,輸出錯誤訊息。
|
||||
|
||||
✅ 非同步程式設計是一種實用的工具。閱讀[更多使用方法](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function)設定非同步程式的程式碼。
|
||||
|
||||
恭喜你!當你建制你的專案(`npm run build`)並在瀏覽器上刷新功能,你有個可以運作的應用套件了!現在只差圖示無法正常顯示,我們會在下一堂課中修正它。
|
||||
|
||||
---
|
||||
|
||||
## 🚀 挑戰
|
||||
|
||||
我們在課程中討論了不同種類的 API。選擇一樣網頁 API 並做更深度的研究。舉例來說,看看瀏覽器內支援的 API 如 [HTML Drag and Drop API](https://developer.mozilla.org/en-US/docs/Web/API/HTML_Drag_and_Drop_API)。依你看,什麼決定了 API 的優劣?
|
||||
|
||||
## 課後測驗
|
||||
|
||||
[課後測驗](https://nice-beach-0fe9e9d0f.azurestaticapps.net/quiz/26?loc=zh_tw)
|
||||
|
||||
## 複習與自學
|
||||
|
||||
這堂課你學會關於 LocalStorage 與 API,它們對資深網頁開發者提供很大的幫助。你能想想這兩樣東西如何彼此相互合作呢?想想你會如何建構你的網頁,讓 API 得以使用你所儲存的資料。
|
||||
|
||||
## 作業
|
||||
|
||||
[認領一項 API](assignment.zh-tw.md)
|
||||
|
@@ -0,0 +1,11 @@
|
||||
# 認領一項 API
|
||||
|
||||
## 大綱
|
||||
|
||||
API 可以是很好玩的。這裡有[許多公開 API 的清單](https://github.com/public-apis/public-apis)。挑選一項 API,建立一個網頁擴充功能來解決問題。問題可以很小,如找不到足夠的寵物照片,這時你可以嘗試使用[dog CEO API](https://dog.ceo/dog-api/));或是解決更大問題。好好享受吧!
|
||||
|
||||
## 學習評量
|
||||
|
||||
| 作業內容 | 優良 | 普通 | 待改進 |
|
||||
| -------- | --------------------------------------------- | ------------------------ | ------------ |
|
||||
| | 使用上述清單內的 API 建立完整的瀏覽器擴充功能 | 建立部分的瀏覽器擴充功能 | 套件存在問題 |
|
Reference in New Issue
Block a user