Skip to content

Home

愛上React的三大理由

2015年3月3日在香港JavaScript和Node.js聚會上的記錄:

今天,我想談談React,一個用於創建用戶界面的JavaScript庫。我在幾個項目中使用過它,並且越多地與它共事,我就越欣賞其功能。我將解釋為什麼我覺得React如此引人入勝,以及為什麼你應該考慮使用它。

作為一名軟件工程師,我明白開發人員每天面臨的挑戰。在使用React之前,寫程式碼經常會讓人感到不適,尤其是在構建用戶界面的時候。可能的狀態有很多,並且測試所有狀態都是不切實際的。你可能會遇到可變DOM問題或無法預測的用戶輸入。你的用戶界面可能行為不正常,或者在大型應用程式中無法良好地擴展。

程式設計是一門藝術,特別是組織復雜性的藝術。在建立UI時,ReactJS幫助您管理這種復雜性。

什麼是 React?

React 是 MVC(Model-View-Controller)中的 'view'。與像MeteorJS這樣的全面框架不同,React 主要專注於 UI。 它由 Facebook 和 Instagram 開發,並被用於他們的生產環境中。例如,您在Facebook.com 上看到的評論框就是一個 React 組件。

為什麼選擇 React?

我將重點關注三個關鍵點:React 組件,效能,以及處理動態數據。

1. React 組件

在我之前作為 MeteorJS 開發人員的角色中,我發現像 Handlebars 或 Spacebars 這樣的傳統模板語言很有限。相反,React 使用組件而不是模板。這種模組化的方法允許更大的靈活性,可重用性和可測試性。

2. 效能

由於發明了虛擬 DOM,React 提供了令人印象深刻的速度。傳統的方法通常需要對整個頁面進行重新渲染,即使是對微小變化也是如此。 虛擬 DOM 通過僅更新 DOM 的變更部分來最小化這種昂貴的操作。

3. 管理動態數據

狀態管理是 UI 開發中的一大挑戰。 React 通過採用單向資料流來解決這個問題,從而提高了可維護性並簡化了調試。

結語

總結,React因其簡單和強大而脫穎而出。它使得可以開發可重複使用、可測試的組件。它提供出色的效能和有效管理動態數據。

就到這裏!有任何問題嗎?

這裡是幻燈片:幻燈片介紹

Common npm Permission Issues

The Problem:

If you are using a Mac and have installed Node.js via a pkg file downloaded from the official website, you are likely to encounter the following error message when you try to install an npm module globally:

npm ERR! Please try running this command again as root/Administrator.

My Solution:

DO NOT use the sudo command to install the package!

sudo npm install module -g

Some people recommend the above solution on Stack Overflow, but I strongly advise against managing packages with sudo. This workaround may temporarily solve your problem, but you'll likely encounter more issues later on.

Here is the recommended approach:

Step 1: Determine your username with the following command:

whoami

For example, my username is victorleungtw.

Step 2: Change the ownership of the node modules folder:

sudo chown -R `whoami` /usr/local/lib/node_modules

After performing these steps, you won't have to use sudo when installing npm packages in the future.

Common npm Permission Issues

The Problem:

Welcome to "Continuous Improvement," the podcast where we discuss practical solutions to everyday tech challenges. I'm your host, Victor, and in today's episode, we'll be tackling a common issue that Mac users face when trying to install npm modules globally.

Have you ever encountered the dreaded error message: "Please try running this command again as root/Administrator" when attempting to install an npm module? You're not alone! In fact, many Mac users who have installed Node.js through the official website have come across this frustrating roadblock.

But fear not, my friends, for I have found a solution that doesn't involve using the sudo command. Today, I'll walk you through the steps to resolve this issue once and for all.

The first thing you need to do is avoid the temptation to rely on that sudo command. Although it may seem like a quick fix, using sudo to install packages can lead to bigger problems down the road. So, let's explore a more sustainable approach.

Step one is to determine your username. To do this, open your terminal and type the following command:

whoami

Once you have your username, which should be displayed in the terminal, we can move on to step two: changing the ownership of the node modules folder. This step is crucial to ensuring a smooth installation process without the need for elevated privileges.

To change the ownership, enter the following command:

sudo chown -R `whoami` /usr/local/lib/node_modules

Now, that might sound like a mouthful, but let me break it down for you. The chown command changes the ownership of a file or directory. By using the backtick operator followed by whoami within the command, we dynamically retrieve our username. Lastly, we specify the directory where Node.js stores its modules by default.

And there you have it! Once you've completed these two steps, you'll no longer need to use sudo when installing npm packages. Enjoy a smoother installation process without the hassle of elevated privileges.

That's all for today's episode of "Continuous Improvement." I hope you found this solution helpful in overcoming the npm module installation error. Don't forget to check out our website for more tips and tricks to enhance your tech journey.

Thank you for tuning in, and remember, continuous learning and improvement are the keys to success. Join us next time on "Continuous Improvement" as we dive into more exciting topics. Until then, happy coding!

常見的 npm 權限問題

問題:

如果你正在使用Mac,並且通過從官方網站下載的pkg文件安裝了Node.js,那麼當你嘗試全局安裝一個npm模塊時,你可能會遇到以下的錯誤信息:

npm ERR! 請嘗試以root /管理員身份再次運行此命令。

我的解決方案:

不要用sudo命令來安裝包!

sudo npm install module -g

有些人在Stack Overflow上推薦上述解決方案,但我強烈建議不要用sudo來管理包。這種解決方案可能會暫時解決你的問題,但你將可能會在以後遇到更多問題。

下面是推薦的做法:

步驟1:使用以下命令確定你的用戶名:

whoami

例如,我的用戶名是victorleungtw。

步驟2:更改node模塊文件夾的擁有權:

sudo chown -R `whoami` /usr/local/lib/node_modules

執行這些步驟後,你將來在安裝npm包時就不必再使用sudo了。

Sublime Text 3: Using the OS X Command Line

The Problem

Sublime Text 3 includes a command line tool, subl. Unfortunately, this tool doesn't work right out of the box after you've installed the editor on OS X Yosemite.

My Solution

After installing Sublime Text 3, create a symbolic link using the following command:

ln -s /Applications/Sublime\ Text.app/Contents/SharedSupport/bin/subl /usr/local/bin/subl

Here,

  • /Applications/Sublime\ Text.app/Contents/SharedSupport/bin/subl is the location where the application is stored in your Applications directory.
  • /usr/local/bin is the chosen path where you want the symbolic link to reside.

To set Sublime Text as the default editor for various commands that prompt for input, configure your EDITOR environment variable as follows:

export EDITOR='subl -w'

The -w flag ensures that the subl command will not exit until the file is closed.

Additionally, you can set Sublime Text as your default Git editor with this command:

git config --global core.editor "subl -n -w"

Sublime Text 3: Using the OS X Command Line

The Problem

Welcome to "Continuous Improvement," the podcast where we explore ways to enhance our workflow and optimize our productivity. I'm your host, Victor, and in today's episode, we'll be discussing a solution to a common problem faced by Sublime Text 3 users on OS X Yosemite.

Let's dive right into it. Many Sublime Text users encounter issues with the command line tool called subl, which refuses to work after the initial installation on OS X Yosemite. This can be frustrating, especially when you rely on Sublime Text for your coding or editing needs.

Fortunately, I have a solution for you. After installing Sublime Text 3, you can create a symbolic link to resolve this issue. Here's how you can do it. Open up your terminal and enter the following command:

ln -s /Applications/Sublime\ Text.app/Contents/SharedSupport/bin/subl /usr/local/bin/subl

Let me break it down for you. The first path, /Applications/Sublime\ Text.app/Contents/SharedSupport/bin/subl, represents the location where Sublime Text is stored in your Applications directory. The second path, /usr/local/bin, is where you want the symbolic link to reside. Once you've created this link, the command line tool subl should start working seamlessly.

But that's not all. If you want to set Sublime Text as your default editor for various commands that prompt for input, follow this next step. Configure your EDITOR environment variable by entering the following command:

export EDITOR='subl -w'

The -w flag ensures that the subl command does not exit until you've closed the file. This is handy when you're working on longer tasks or editing multiple files at once.

Lastly, if you're using Git and prefer Sublime Text as your default editor for commit messages and other Git-related activities, here's what you need to do. Use this command:

git config --global core.editor "subl -n -w"

This command sets Sublime Text as your default Git editor. The -n flag opens each file in a new window, ensuring a clutter-free editing experience. The -w flag, as we discussed before, ensures that the command doesn't exit until you're done editing.

And there you have it! A simple solution to get Sublime Text 3 up and running smoothly on OS X Yosemite. Don't let technical hurdles slow you down when you're striving for continuous improvement and peak efficiency.

That's all for today's episode of "Continuous Improvement." I hope you found this information helpful for optimizing your workflow with Sublime Text 3. Be sure to tune in next time for more tips and tricks to enhance your productivity. Until then, I'm Victor, signing off.

Sublime Text 3:使用 OS X 命令列

問題

Sublime Text 3 包括一個命令行工具, subl。 不幸的是,當你在 OS X Yosemite 上安裝了編輯器後,這個工具無法直接工作。

我的解決方法

安裝Sublime Text 3後,使用以下命令創建一個符號鏈接:

ln -s /Applications/Sublime\ Text.app/Contents/SharedSupport/bin/subl /usr/local/bin/subl

在這裡,

  • /Applications/Sublime\ Text.app/Contents/SharedSupport/bin/subl 是應用程式在您的應用程式目錄中的存放位置。
  • /usr/local/bin 是您希望符號鏈接存在的選擇路徑。

要將Sublime Text設置為各種命令的默認編輯器,該命令提示輸入,請按照如下方式配置您的 EDITOR 環境變量:

export EDITOR='subl -w'

-w 標誌確保 subl 命令在文件關閉之前不會退出。

另外,您可以使用此命令將Sublime Text設置為您的默認Git編輯器:

git config --global core.editor "subl -n -w"

12 Things You Need To Know About ECMAScript 6

ECMAScript 6 is the next version of the JavaScript standard.\

Here are the 12 cool things you need to know about ES6:

1. Arrow Functions

Similar to CoffeeScript, ES6 allows you to define a function using the fat arrow syntax.

var square = n => n * n

2. Arrow Scope

The keyword ‘this’ can be confusing as it refers to whatever invokes it. For example, ‘this’ refers to the window object when using setTimeout. This issue is resolved by the arrow function expression, which binds ‘this’ to the function itself.

function yo() {
  this.name = "Victor"
  setTimeout(() => {
    console.log("yo " + this.name)
  }, 5000)
}
// Output: yo Victor

3. String Templates

Like CoffeeScript, ES6 includes a string interpolation feature using the ${} syntax for variables. Notice that the example below uses a back-tick character instead of single quotes on line 2.

var person = { name: "Victor", age: 24 }
var hello = `My name is ${person.name} and I am ${person.age} years old`

4. Let Scope

The let statement declares a block-scope local variable. In other words, it does not override the value of the variable in the outer scope.

var x = 10
for (let i = 0; i < 10; i++) {
  let x = i * 2
}
console.log(x) // x is still 10, not 18

5. Destructuring Arrays

Instead of declaring multiple variables one by one, you can assign them in one line like this:

var [one, two, three] = [1, 2, 3]

6. Destructuring Objects

Similarly, you can use destructuring for objects as well:

var { firstName: name } = { firstName: "Victor" }

7. Object Literals

You can use shorthand notation to construct an object, instead of writing {firstName: firstName, lastName: lastName}.

var firstName = "Victor",
  lastName = "Leung"
var person = { firstName, lastName }

8. Default Arguments

You can assign default values to arguments like this:

function sayHello(name, greeting = "yo man") {
  return `${greeting} ${name}`
}

9. Spread Operator

The spread operator (...) allows you to pass each element of an array as an argument.

function threeNumbers(x, y, z) {
  console.log(x, y, z) // 0, 1, 2
}
var args = [0, 1, 2]
threeNumbers(...args)

10. Classes

Much like other object-oriented programming languages, ES6 allows you to define a blueprint for constructing objects using the new class syntax.

class Person {
  sayHey(name) {
    return "hey " + name
  }
}

11. Class Inheritance

You can use the extends keyword to extend a class.

class Victor extends Person {
  sayHey() {
    return super.sayHey("Victor")
  }
}

12. Generators

Generators are functions that can be exited and later re-entered. Calling a generator function does not execute its body immediately. When the iterator’s next() method is called, the generator function's body is executed until the first yield expression.

function* idMaker() {
  var index = 0
  while (true) yield index++
}

var gen = idMaker()

console.log(gen.next().value) // 0
console.log(gen.next().value) // 1
console.log(gen.next().value) // 2

There are many new features in ECMAScript 6. For more details, please refer to the MDN. The official publication process began in Mozilla in March 2015 and is expected to be completed in June 2015. Stay tuned!

12 Things You Need To Know About ECMAScript 6

ECMAScript 6 is the next version of the JavaScript standard.\

Welcome to another episode of Continuous Improvement. I'm your host, Victor, and today we're going to dive into the exciting world of ECMAScript 6, the next version of the JavaScript standard. I'm going to share with you 12 cool things you need to know about ES6. So, let's get started!

First up, we have arrow functions. Similar to CoffeeScript, ES6 allows you to define a function using the fat arrow syntax. For example, you can write var square = (n) => n * n; to define a function that squares a number.

Moving on, we have arrow scope. In JavaScript, the keyword 'this' can sometimes be confusing as it refers to whatever invokes it. However, ES6 introduces arrow function expressions, which binds 'this' to the function itself. This resolves the issue and provides a clearer understanding of the context in which 'this' is used.

Now, let's talk about string templates. ES6 includes a string interpolation feature using the ${} syntax for variables. This means you can construct strings in a more concise and readable way. For example, with ES6, you can write var hello =My name is ${person.name} and I am ${person.age} years old; to build a string with dynamic values.

Next, we have let scope. The let statement in ES6 declares a block-scope local variable. This means that it doesn't override the value of the variable in the outer scope, giving you more control over variable scope and avoiding potential bugs.

Moving on, we come to destructuring arrays. Instead of declaring multiple variables one by one, ES6 allows you to assign them in one line using array destructuring. This is especially useful when working with arrays that contain multiple values.

Similarly, you can also use destructuring for objects. With ES6, you can easily extract values from an object and assign them to variables using object destructuring syntax.

Object literals are another cool feature of ES6. Instead of writing out key-value pairs explicitly, you can use shorthand notation to construct an object. This makes the code shorter and more readable.

ES6 also introduces default arguments. When defining a function, you can assign default values to arguments. This way, if an argument is not provided when the function is called, it will use the default value instead.

Next up, we have the spread operator. This operator, denoted by the three-dots (...), allows you to pass each element of an array as an argument to a function. It simplifies the process of passing array elements individually.

Classes are a fantastic addition to ES6. Similar to other object-oriented programming languages, ES6 allows you to define a blueprint for constructing objects using the new class syntax. This provides a more structured and organized way to create objects with consistent behavior.

With class inheritance in ES6, you can now extend a class by using the 'extends' keyword. This allows you to create specialized classes that inherit properties and methods from a parent class, giving you the power to build complex object hierarchies.

Last but not least, we have generators. Generators are functions that can be exited and later re-entered. Calling a generator function does not immediately execute its body. Instead, when the iterator's next() method is called, the generator function's body is executed up to the first yield expression. This provides a powerful mechanism for controlling the flow of execution and creating efficient asynchronous code.

And there you have it, folks! These were the 12 cool things you need to know about ECMAScript 6. This new version of the JavaScript standard brings a lot of exciting features and enhancements that will make your code more robust, readable, and maintainable.

Thank you for tuning in to this episode of Continuous Improvement. I hope you found this exploration of ES6 enlightening and inspiring. If you want to learn more about ES6, head over to the MDN website at [MDN link]. Stay tuned for more episodes where we'll continue to explore ways to improve our skills as developers. Until then, keep coding and keep improving!

你需要知道的關於ECMAScript 6的12件事

ECMAScript 6 是 JavaScript 標準的下一個版本。

以下是您需要知道的有關 ES6 的12個酷事:

1. 箭頭函數

類似於 CoffeeScript,ES6 允許你使用肥箭頭語法定義一個函數。

var square = n => n * n

2. 箭頭範疇

‘this’關鍵字可能會令人困惑,因為它指的是調用它的東西。例如,當使用 setTimeout 時,‘this’ 指的是窗口物件。箭頭函數表達式解決了這個問題,將‘this’綁定到函數本身。

function yo() {
  this.name = "Victor"
  setTimeout(() => {
    console.log("yo " + this.name)
  }, 5000)
}
// Output: yo Victor

3. 字串模板

就像 CoffeeScript 一樣,ES6 包含了一個使用 ${} 語法用於變數的字串內插特性。注意下面的例子在第 2 行使用了反勾號而非單引號。

var person = { name: "Victor", age: 24 }
var hello = `My name is ${person.name} and I am ${person.age} years old`

4. Let 範疇

let 聲明了一個區塊範疇的本地變數。換句話說,它不會覆寫外部範疇中的變數值。

var x = 10
for (let i = 0; i < 10; i++) {
  let x = i * 2
}
console.log(x) // x is still 10, not 18

5. 陣列解構賦值

您不必逐一聲明多個變數,可以像這樣在一行中賦值給它們:

var [one, two, three] = [1, 2, 3]

6. 物件解構賦值

同樣地,您也可以為物件使用解構賦值:

var { firstName: name } = { firstName: "Victor" }

7. 物件字面量

您可以使用簡寫符號來構造一個物件,而不是寫 {firstName: firstName, lastName: lastName}

var firstName = "Victor",
  lastName = "Leung"
var person = { firstName, lastName }

8. 默認參數

您可以像這樣為參數分配默認值:

function sayHello(name, greeting = "yo man") {
  return `${greeting} ${name}`
}

9. 展開運算符

展開運算符(...)允許您將一個陣列的每個元素作為參數傳遞。

function threeNumbers(x, y, z) {
  console.log(x, y, z) // 0, 1, 2
}
var args = [0, 1, 2]
threeNumbers(...args)

10. 類別

就像其他物件導向的程式設計語言一樣,ES6 允許您使用新的類別語法來定義一個用於構建物件的藍圖。

class Person {
  sayHey(name) {
    return "hey " + name
  }
}

11. 類別繼承

您可以使用 extends 關鍵字來擴展一個類別。

class Victor extends Person {
  sayHey() {
    return super.sayHey("Victor")
  }
}

12. 產生器

產生器是可以被退出並稍後重新進入的函數。調用一個產生器函數並不會立即執行其內容。當迭代器的 next() 方法被調用時,產生器函數的內容會被執行,直到遇到第一個 yield 表達式。

function* idMaker() {
  var index = 0
  while (true) yield index++
}

var gen = idMaker()

console.log(gen.next().value) // 0
console.log(gen.next().value) // 1
console.log(gen.next().value) // 2

ECMAScript 6中有許多新特性。更多細節,請參考 MDN。官方發表過程於2015年3月在Mozilla開始,並預計於2015年6月完成。敬請期待!