For English version, please scroll down.
今天我們就 JavaScript 及其運行環境:瀏覽器,如何操作 DOM, 事件, 函式庫 D3, 最後畫一個小地圖作結。
以下的範例可以在我們每次在頁面上點了滑鼠之後,
更新畫面上顯示的點擊次數
const reading = document.querySelector(`#count`)
let count = 0
document.addEventListener(`click`, (event)=>{
count = count + 1
reading.innerHTML = `Count: ${count}`
})
https://codepen.io/owlfox/pen/bGbyZjV
程式語言裡常出現 "物件/Object" 的概念,大概可以想成把相關連的資料、程式分類擺好以利使用。
JavaScript(後簡稱為JS)是在 1995 年,那個 IE, Chrome, Firefox 還不知道在那裡的年代,由一位 Brendan Eich 先生爲 Netscape 這家公司的網路瀏覽器開發的程式語言。
這個“語言”讓我們可以交代瀏覽器在打開了一個超連接,讀取網頁的 html 檔案、把網頁畫出來之後,可以依跟使用者的輸入做出一些互動。
JS 後來被許多瀏覽器廠家採用,European Computer Manufacturers Association (ECMA) 這個組織後來主導了 JS 語言的語法,讓各瀏覽器可以執行相同的程式,得到相同的結果。而這個協定有各種不同版本,我們也叫 JavaScript EcmaScript,所以你會看到以 ES2015/ES6 來稱呼的 JS 語言版本。如果想知道一些新的 JS, CSS 語法在各瀏覽器上是不是都有實作,可以參考 caniuse 網頁上的資訊。
DOM 就是 Document Object Model ,基本上就是個每個英文字都知道意思,但是拼起來就不知道是什麼的術語。這裡我是想成各家瀏覽器在收到 html 文件之後都會以自己的邏輯把資料存好供 JS 跟 CSS 存取。而 W3C 制定的規範就是要求大家都把資料依照類似的結構整理好,讓不同的程式碼得到相同的執行成果。 我們在上面的例子裡面就是透過 JS 對 DOM 進行一個操作的動作。
寫程式時常會有不如預期、需要除錯的時候。我們的瀏覽器除了可以用來看,還可以用來幫我們找錯誤。當你在網頁上點右鍵->查看元素的之後,瀏覽器會開出一個小視窗顯示 html 的原始碼,其對應的 CSS 風格、你也可以 source
分頁在 JS 裡面加入中斷點,在 console 裡面直接寫 JS 原始碼,觀察錯誤訊息、程式運行狀態,以及在網路分頁裡面看看這個網頁下載了哪些檔案,跟背地裡送/拿了哪些資料。
底下出現的範例基本上你都可以直接貼到 console 裡面去看結果,
因為系列文章有用到,這裡稍微介紹一下 ES6 的語法。
class Animal {
constructor(name) {
this.name = name
}
printName() {
console.log(this.name)
}
}
class Dog extends Animal {
bark() {
console.log(`${this.name}: Bow!`)
}
}
let beddy = new Dog("beddy")
beddy.bark()
//beddy: Bow!
let a = [1,2,3]
let b = [...a, 4] //[1,2,3,4]
或是把函數的參數組織成一個陣列
function f(...args){
return args.filter(e=>e===1)
}
f(1,2,3,4) //return [1]
let a, b = 1, 2
[a,b] = [b,a]
let a = {name:"beddy", age: -1}
let {name, age} = a
string、number、boolean、null、undefined、symbol
,還有其他的各種物件。當我們在操作/指定變數內容的時候,只有 Primitive 會在記憶體中實際複製一份,而大多情況我們只是給個物件的Reference。let a = 2
let b = a
b = 3
console.log(a,b)
//2,3 a real copy
let c = [1]
let d = c
d.push(2)
console.log(c,d)
//[1,2] [1,2] just a reference,
//you are playing the same object
const places = ["高雄", "台灣", "宇宙"]
const slogans = places.map(e=>e+"發大財")
// slogans 變成 ["高雄發大財", "台灣發大財", "宇宙發大財"]
還記得以前每次滑鼠點網頁總是要重新整理、載入一陣子才有畫面嗎?如果沒有這段記憶,我們的年紀可能差得有點多了。
在 1999 微軟發明 AJAX 之後,網頁瀏覽器具備了可以在不重新整理頁面也能取得所需資料的超能力。請看如下範例網頁:
https://www.maptiler.com/google-maps-coordinates-tile-bounds-projection/
在我們每次縮放的時候,其實瀏覽器都有按照寫好的 JS 指令要求去拿各個不同解析度的圖檔,在以前,每次縮放可都是要重新整理一次頁面呢。如果今天的網頁地圖是這樣,想必很多人用不下去吧。
前面提到的大多是任何瀏覽器都有支援的原生函數/語法。
軟體世界有個名言是不要重複造輪子。幾乎任何程式語言、任何你想得到的功能,只要你找對方向,幾乎都能找到網路上的朋友寫好的函式庫。而上提到的 module 語法就可以用來包裝/引用各種方便的 JS 套件。
例如原生的 document.selector
有點繁複的等語法在一套名為 D3.js 裡會變得比較簡潔一點,另外 D3 也可以用來幫我們繪製地圖以及相關圖表。
範例:
http://bl.ocks.org/owlfox/198b5deaacf59a0495513c6dba239943
這裡我拿參考書籍裡的程式碼來做範例(不好意思我還在找合用的台灣地圖資料)。這裡我們需要引用外部的JS函式庫來協助開發,關於如何在 HTML 裡執行 JS,請參考這篇。
這裡我們有用到外部的 json 檔案、D3 JS 我們下次再來介紹..
===
ironman
Today we are going to show you things about JavaScript, its running environement: browser, how to play with dom, event, D3 and draw a small map as an ending.
By clicking the example page in the link below, we can see the number increases.
const reading = document.querySelector(`#count`)
let count = 0
document.addEventListener(`click`, (event)=>{
count = count + 1
reading.innerHTML = `Count: ${count}`
})
https://codepen.io/owlfox/pen/bGbyZjV
"object" is a common term/concept in programming. Here you can treat it as packing related information/code together for easy access.
As for the codes above
document
is a global object available while JS running in browser. It is the actual data structure of the HTML after being parsed by the browser.querySelector
method in document
object, ask it to search an element in html with id
equals to could
, and then return the result to the constant variable reading
reading
elementJavaScript( hereinafter called JS)was crafted by Mr. Brendan Eich, who was working for Netscape at 1995. It was a language designed to be executed on their own browser at a time which IE, Chrome, Firefox were not exist.
This langualge enables the browser to interact with user inputs after opened the url, fetched html file and rendered the stuff in the window.
JS is adopted by the rest of the browsers. Then here comes European Computer Manufacturers Association (ECMA), organizing with different companies, make a JS specification, allows the same JS file to be able to be runned on different browsers and comes out the same results. There are different versions of the specm and we also call JavaScript as EcmaScript. Sometimes you might find a version of JS called ES2015/ES6. That's the most popular one at the moment. If you would like to know if a spec of JS or CSS is available on different browsers check the website named caniuse.
DOM, Document Object Model, a jargon you know the meaning of every words while have no idea what it is when they write together. Here I think it as the strickly structured format of how different vendors of browser store the parsed html file into a object for JS and CSS to access. W3C is the organization to draft and release the spec of DOM and many other stuff. The above is an example of manuplating DOM.
While we were developing our code/service, unexpected errors/behaviours happen from time to time. For web application, our browser could also be an helpful tool to find where went wrong. Right click on the page -> inspect element will pop a small window to display the source html code of the page, the CSS styles applied. While in the source
tab, you can also add break points in your code to inspect the states of the program at a specific line of code. As for consle
tab, you can write code there to see the results, error message, runtime states. Lastly the network
tab shows you when and what browser requested/sent with this web application.
For the example code below you can just paste them into the console to see the results.
Below is the list of ES6 syntaxs we will use during the series:
map, filter
functions。class Animal {
constructor(name) {
this.name = name
}
printName() {
console.log(this.name)
}
}
class Dog extends Animal {
bark() {
console.log(`${this.name}: Bow!`)
}
}
let beddy = new Dog("beddy")
beddy.bark()
//beddy: Bow!
let a = [1,2,3]
let b = [...a, 4] //[1,2,3,4]
or pack arguments of function into a array
function f(...args){
return args.filter(e=>e===1)
}
f(1,2,3,4) //return [1]
let a, b = 1, 2
[a,b] = [b,a]
let a = {name:"beddy", age: -1}
let {name, age} = a
string、number、boolean、null、undefined、symbol
, and many other objects。 while we were assigning value to a variable, primitive typed value will get copied while others are just a reference.let a = 2
let b = a
b = 3
console.log(a,b)
//2,3 a real copy
let c = [1]
let d = c
d.push(2)
console.log(c,d)
//[1,2] [1,2] just a reference,
//you are playing the same object
const places = ["高雄", "台灣", "宇宙"]
const slogans = places.map(e=>e+"發大財")
// slogans 變成 ["高雄發大財", "台灣發大財", "宇宙發大財"]
Do you have a memory of clicking a webpage and every time you clicked you have to wait the browser to reload the page, which is quite annoying? If not, dont talk to me!
Our browser comes with ability to fetch the data without reloading the pack since 1999, AJAX crafted by Microsoft. See the example below:
https://www.maptiler.com/google-maps-coordinates-tile-bounds-projection/
While we were pan/zooming the map, browser fetched the pictures of different resolution under the hood. It would be quite frustratingunusable if we have to reload the page every time we interact with the map.
Above are the objects, syntaxes supported out of the box, or say VanillaJS.
"Dont reinvent the wheel" is a famous quote from software sommunity. You can find nearly every feature/function you need from the internet written by someone else. The "module" tool above is to help us reuse the works done by the world.
Like the document.selector
syntax abobe, you can use a library called D3.js to make them shorter and easier to read/maintain. D3 can also be used to draw graph, maps and many other things!
example:
http://bl.ocks.org/owlfox/198b5deaacf59a0495513c6dba239943
The above code is adopted from the book in the reference, I am still trying to find a good Taiwan geodat though.. For the information of how to import JS library/file, please have a look at this article。
There are json files and many d3.js codes involved, we will continue our study tomorrow(?)