- EmberJS 教程
- EmberJS - 主頁
- EmberJS - 概述
- EmberJS - 安裝
- EmberJS - 核心概念
- 建立和執行應用程式
- EmberJS - 物件模型
- EmberJS - 路由器
- EmberJS - 模板
- EmberJS - 元件
- EmberJS - 模型
- EmberJS - 管理依賴項
- EmberJS - 應用關注點
- EmberJS - 配置 Ember.js
- EmberJS - Ember 檢查器
- EmberJS 有用資源
- EmberJS - 快速指南
- EmberJS - 有用資源
- EmberJS - 討論
EmberJS - 指定路由模型
可以透過在路由中定義模板名稱來指定路由模型,該名稱與資料模板的名稱相同,並實現其模型掛鉤。
Ember.Route.extend ({
model: function() {
return { //value-1 },{ //value-2 },{..},{ //value-n };
}
});
在上述程式碼中,value-1 到 value-n 變數用於儲存在模板中呼叫的值。
下表列出了不同型別指定路由模型的取值−
| 序號 | 指定路由和說明 |
|---|---|
| 1 | 動態模型
它定義了路由和動態片段,Ember 用它來訪問 URL 中的值。 |
| 2 | 多個模型
可以使用 `RSVP.hash` 定義多個模型,它進一步使用物件來返回 promise。 |
示例
以下示例展示瞭如何指定一個用於顯示資料的路由。建立一個新的路由,如前幾章所述。現在,開啟 `router.js` 檔案,並使用以下程式碼來定義 URL 對映−
import Ember from 'ember';
//Access to Ember.js library as variable Ember
import config from './config/environment';
//It provides access to app's configuration data as variable config
//The const declares read only variable
const Router = Ember.Router.extend ({
location: config.locationType,
rootURL: config.rootURL
});
Router.map(function() {
this.route('specifyroute');
});
//It specifies Router variable available to other parts of the app
export default Router;
建立 `application.hbs` 檔案,並新增以下程式碼−
//link-to is a handlebar helper used for creating links
{{#link-to 'specifyroute'}}Click here to see details{{/link-to}}
{{outlet}} //It is a general helper, where content from other pages will
appear inside this section
開啟在 `app/templates/` 下建立的 `specifyroute.hbs` 檔案,並使用以下程式碼−
<h2>List of Players</h2>
<ul>
//The <i>each</i> helper to loop over each item in the array provided from model() hook
{{#each model as |player|}}
<li>{{player}}</li>
{{/each}}
</ul>
{{outlet}}
要構造 URL,需要實現模型來返回值−
import Ember from 'ember';
export default Ember.Route.extend ({
//The model() method returns the data which you want to make available to the template
model() {
return ['MS Dhoni', 'Steve Smith', 'Jason Roy','AB de Villiers','Kane Williamson'];
}
});
輸出
執行 ember 伺服器,你將收到以下輸出−
當你在輸出中點選連結,它將生成如下截圖中的結果−
emberjs_router.htm
廣告