DIV CSS 佈局教程網

用 Ember.js 做一個 Todo 應用:從 Ember.Application 到 computed property 的逐步實作
編輯:關於JavaScript     

Ember.js 是個「約定大於配置」的框架,它把 MVC 三層都幫你準備好了。第一次上手最容易迷路的地方不是語法,而是不知道該把程式碼放哪一層。用一個 Todo 應用把整條路走一遍,是最快的理解方式。

目標與準備

要做出的效果:文字框輸入內容後按 Enter 新增一筆代辦事項,可以選擇優先級,完成的項目可以刪除。

需要三個函式庫:Ember.js、Handlebars(模板)、jQuery(Ember 內部依賴)。先把骨架搭起來:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Ember--第一個應用</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src=".../handlebars-1.0.rc.1.js"></script>
<script src=".../ember-1.0.0-pre.2.min.js"></script>
</head>
<body>
</body>
</html>

Step 1:建立應用實例

一切從 Ember.Application.create() 開始,它同時也是整個應用的命名空間。Ember 提供了縮寫 Em,而 Em.Logger 就等於 window.console,可以拿來除錯。

window.App = Ember.Application.create({
  ready: function () {
    Em.Logger.info('歡迎使用待辦事項應用');
  }
});

/********************
 model
********************/

/********************
 view
********************/

/********************
 controller
********************/

把註解區塊先寫上,是 Ember 開發的習慣:三層各歸其位,之後就知道新程式碼該丟哪。

Step 2:輸入框視圖

Ember 有 Ember.View(用 create 或 extend)可以造任何視圖,但文字框有現成的 Ember.TextField 可直接擴充:

App.AddItemView = Ember.TextField.extend({
  placeholder: '輸入待辦事項',
  insertNewline: function () {
    // 暫時留空
  }
});

placeholder 直接用 HTML5 原生屬性;insertNewline 是 Ember 提供的掛勾,使用者在輸入框按 Enter 時自動觸發——這比我們自己去綁 keydown 判斷 keyCode 乾淨得多。

Step 3:列表視圖

清單用 Ember.CollectionView,它預設有一個 content 屬性存放項目資料(陣列)。要讓它渲染成 ul,得指定 tagName:

App.ListView = Ember.CollectionView.extend({
  content: ['a', 'b', 'c'],
  tagName: 'ul'
});

Step 4:用 Handlebars 把視圖放上頁面

視圖只是定義,還沒渲染。Ember 用 Handlebars 模板掛載,寫法是 script type="text/x-handlebars",用雙花括號呼叫「視圖助手」:

<body>
<script type="text/x-handlebars">
  <span>請輸入待辦事項:</span>{{view App.AddItemView}}<br/>
  {{view App.ListView}}
</script>
</body>

此時重新整理,會看到提示文字與一個文字框;列表因為沒有指定項目模板,只會出現三個空的項目符號。這正好說明 Ember 的資料流:content 有值,但沒有 itemViewClass 與模板,就什麼都不顯示。

Step 5:定義列表項目模板

用 itemViewClass 指定每一項怎麼渲染,並給它一個模板名稱:

App.ListView = Ember.CollectionView.extend({
  content: ['a', 'b', 'c'],
  tagName: 'ul',
  itemViewClass: Ember.View.extend({
    templateName: 'itemTemplate'
  })
});

然後在 HTML 裡補上對應名稱的模板,用 view.content 取到當前項目:

<script type="text/x-handlebars" data-template-name="itemTemplate">
  {{view.content}}
</script>

重新整理,內容出現了,而且 Ember 自動幫你加上 li 標籤。

Step 6:用 ArrayController 做雙向綁定

資料當然不能寫死。Ember 的 ArrayController 會把你傳進去的普通陣列轉為 Ember 陣列,支援綁定:

App.todoStore = Ember.ArrayController.create({
  content: []
});

App.ListView = Ember.CollectionView.extend({
  contentBinding: 'App.todoStore',   // 綁定到 todoStore
  tagName: 'ul',
  itemViewClass: Ember.View.extend({
    templateName: 'itemTemplate'
  })
});

Binding 是後綴約定,值是要綁定的物件路徑,預設取對方的 content。從此兩邊同步:改陣列,畫面變;改畫面,陣列也變。

Step 7:按下 Enter 就新增

App.AddItemView = Ember.TextField.extend({
  placeholder: '輸入待辦事項',
  elementId: 'add',
  insertNewline: function () {
    var item = this.get('value');
    App.todoStore.pushObject(item);
    this.set('value', '');      // 清空輸入框
  }
});

get() 讀屬性、set() 寫屬性、pushObject() 推入陣列——Ember 一律走這組方法而非直接存取,才能觸發綁定更新。這點是 Ember 1.x 的強制規定,也是很多人卡住的地方。

Step 8:加上優先級下拉選單

Ember 也有現成的 Ember.Select,同樣靠綁定運作:

App.selectController = Ember.Object.create({
  selected: '低',
  content: ['高', '中', '低']
});
<script type="text/x-handlebars">
<span>請輸入待辦事項:</span>{{view App.AddItemView}}<br/>
<span>請選擇優先級:</span>{{view Ember.Select
  contentBinding="App.selectController.content"
  selectionBinding="App.selectController.selected"}}
{{view App.ListView}}
</script>

contentBinding 綁選項清單,selectionBinding 綁目前選中值。

Step 9:引入 Model 與 computed property

現在列表項只是純字串,沒辦法各自攜帶優先級。該 model 上場了:

App.TodoModel = Em.Object.extend({
  status: '',            // 優先級
  value: '',             // 輸入的內容
  title: function () {
    return '[' + this.get('status') + ']' + this.get('value');
  }.property('status', 'value')   // 宣告為計算屬性
});

重點是 .property('status', 'value'):它把一個函式變成計算屬性,並宣告它依賴哪些欄位。只要 status 或 value 任一變動,title 就會自動重算並通知綁定它的模板更新。這是 Ember 最漂亮的功能之一,完全不必手動觸發刷新。

新增時改成建立 model 實例,並同時取決於兩個來源的值:

App.AddItemView = Ember.TextField.extend({
  placeholder: '輸入待辦事項',
  elementId: 'add',
  insertNewline: function () {
    var item = App.TodoModel.create({
      status: App.selectController.get('selected'),
      value: this.get('value')
    });
    App.todoStore.pushObject(item);
    this.set('value', '');
  }
});

模板改成顯示 title:

<script type="text/x-handlebars" data-template-name="itemTemplate">
  {{view.content.title}}
</script>

Step 10:刪除

新增用 pushObject,刪除就用 removeObject。因為刪除連結位於每個項目之內,方法要掛在 itemViewClass 上:

App.ListView = Ember.CollectionView.extend({
  contentBinding: 'App.todoStore',
  tagName: 'ul',
  itemViewClass: Ember.View.extend({
    templateName: 'itemTemplate',
    removeItem: function () {
      this.getPath('contentView.content').removeObject(this.get('content'));
    },
    mouseEnter: function () { this.set('hover', true); },
    mouseLeave: function () { this.set('hover', false); }
  })
});

模板裡用 action 助手觸發,並用 {{#if}} 做條件顯示,讓刪除鈕只在滑過時出現:

<script type="text/x-handlebars" data-template-name="itemTemplate">
  {{view.content.title}}
  {{#if view.hover}}
    <a href="#" {{action removeItem target="this"}}>X</a>
  {{/if}}
</script>

回頭看:Ember 1.x 教了我們什麼

  • 命名空間即架構:App.Model / App.XxxView / App.xxxController,位置本身就是文件。
  • 綁定取代手動更新:contentBinding、selectionBinding,宣告關係而非寫流程。
  • get / set 是強制介面:繞過它就繞過了整套觀察者機制。
  • computed property 取代 derived 欄位:.property() 之後的字串就是依賴清單。

不過必須誠實說:以上是 Ember 1.0 pre 系列的寫法,Ember.Object、Ember.Select、contentBinding、itemViewClass 這些 API 後續都經歷了大幅變革。Ember Octane 之後改成 Glimmer 元件、原生的 @tracked 裝飾器、以及 <template> 標籤與 ...attributes,View 層幾乎完全重寫。所以這篇的價值請當作「理解 Ember 的綁定與計算屬性思想」,而不是可以照抄的現代教學。而現在要寫 Todo 應用,React、Vue、Svelte 或甚至單檔 HTML 加原生 JS 都會是更實際的選擇。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved