Ember 拥有丰富多样的插件生态系统,这些插件能够轻松的应用到工程中。插件经常能为工程添加大量的功能,省时省力的同时,让你能够更好的集中精力到你的项目上。
要浏览插件,请访问 Ember Observer 网站。它将发布到 NPM 的 ember 插件分门别类,同时根据一系列的标准对这些插件进行了评分。
对于“超级租赁”,我们将利用如下两个插件: ember-cli-tutorial-style 和 ember-cli-mirage。
ember-cli-tutorial-style
我们创建了一个名叫 ember-cli-tutorial-style 的插件即刻来为教程添加样式,而非让你复制和粘贴 CSS 来给 Super Rentals 添加样式。这个插件通过创建一个名叫 ember-tutorial.css
的文件,然后将这个文件放置到 super-rentals 的 vendor
(它在 app/index.html
中被应用了)目录来实现相应效果。我们可以为 vendor/ember-tutorial.css
添加额外的样式修改,所有的修改将会在我们重启 app 时生效。
请运行如下命令来安装插件:
ember install ember-cli-tutorial-style
既然 Ember 插件是 npm 包,那么 ember install
将把它们安装在 node_modules
目录,并且在 package.json
中为其生成一个入口。成功安装插件之后,请确保重启你的服务器。重启服务器将引入新的 CSS 文件,当你刷新浏览器时,你会看到如下界面:
ember-cli-mirage
Mirage 是一个客户端的 HTTP 存根库,它经常被用于 Ember 的验收测试。对于本教程的情况,我们将使用 mirage 作为我们的源数据。Mirage 将让我们在开发时可以通过伪造数据来模仿一个后台服务器工作。
请像下面这样安装 Mirage 插件:
ember install ember-cli-mirage
如果你在另一个 shell 里运行 ember serve
,请重启服务器以引入你创建的 Mirage。
现在,让我们通过更新 mirage/config.js
来配置 Mirage ,使得我们可以发送上面已经定义的租借信息:
mirage/config.js
export default function() {
this.namespace = '/api';
this.get('/rentals', function() {
return {
data: [{
type: 'rentals',
id: 'grand-old-mansion',
attributes: {
title: 'Grand Old Mansion',
owner: 'Veruca Salt',
city: 'San Francisco',
type: 'Estate',
bedrooms: 15,
image: 'https://upload.wikimedia.org/wikipedia/commons/c/cb/Crane_estate_(5).jpg'
}
}, {
type: 'rentals',
id: 'urban-living',
attributes: {
title: 'Urban Living',
owner: 'Mike Teavee',
city: 'Seattle',
type: 'Condo',
bedrooms: 1,
image: 'https://upload.wikimedia.org/wikipedia/commons/0/0e/Alfonso_13_Highrise_Tegucigalpa.jpg'
}
}, {
type: 'rentals',
id: 'downtown-charm',
attributes: {
title: 'Downtown Charm',
owner: 'Violet Beauregarde',
city: 'Portland',
type: 'Apartment',
bedrooms: 3,
image: 'https://upload.wikimedia.org/wikipedia/commons/f/f7/Wheeldon_Apartment_Building_-_Portland_Oregon.jpg'
}
}]
};
});
}
这样配置 Mirage 使得每当 Ember Data 发起一个链接到 /api/rentals
的 GET 请求的时候,Mirage 将返回这一个 JavaScript 对象的 JSON 的形式。为了让它正常运行,我需要让我们的应用默认访问 /api
的命名空间。如果没有这些配置,我们应用中/rentals
的导航将和 Mirage 产生冲突。
为了实现它,我们可以生成一个应用适配器(adapter)。
ember generate adapter application
这个适配器将基于 Ember Data 的类来扩展 JSONAPIAdapter
:
app/adapters/application.js
import DS from 'ember-data';
export default DS.JSONAPIAdapter.extend({
namespace: 'api'
});