模型钩子
现在,让我们在 index 模板添加一个可租借信息列表。我们知道,租借信息不会是静态的,因为用户最后需要能够添加、更新、删除它们。因为这个原因,我们需要一个租借信息模型来保存租借信息。简单起见,一开始我们将使用硬编码的 JavaScript 数组对象。稍后,我们将切换到使用 Ember Data,它是我们的 app 中一个强力的 数据管理库。
这会是我们主页已完成时候的样子:
在 Ember 里,路由处理程序将负责加载模型中的数据。让我们打开 app/routes/rentals.js
,然后将我们硬编码的数据添加到其中作为模型钩子的返回值:
app/routes/rentals.js
import Ember from 'ember';
let rentals = [{
id: 'grand-old-mansion',
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'
}, {
id: 'urban-living',
title: 'Urban Living',
owner: 'Mike TV',
city: 'Seattle',
type: 'Condo',
bedrooms: 1,
image: 'https://upload.wikimedia.org/wikipedia/commons/0/0e/Alfonso_13_Highrise_Tegucigalpa.jpg'
}, {
id: 'downtown-charm',
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'
}];
export default Ember.Route.extend({
model() {
return rentals;
}
});
这里,我们使用了 ES6 中的方法定义的缩写方式: model()
相当于是 model: function ()
。
model
函数表现的像一个钩子,这意味着 Ember 将在我们 app 中的不同时间去调用它。我们添加到我们 rentals
路由处理程序中的模型钩子将在一个用户进入到 rentals
路由是被调用。
model
钩子返回我们的租借信息数组,然后将它传递到我们的 rentals
模板来作为 model
的值。
现在,让我们继续看我们的模板。我们可以使用模型数据来展示我们的租赁信息列表。这里,我们将使用另外一个常用的叫做 {{each}} 的 Handlebars helper。这一个 helper 将让我们循环遍历模型中的每一个对象。
app/templates/rentals.hbs
<div class="jumbo">
<div class="right tomster"></div>
<h2>Welcome!</h2>
<p>
We hope you find exactly what you're looking for in a place to stay.
<br>Browse our listings, or use the search box below to narrow your search.
</p>
{{#link-to 'about' class="button"}}
About Us
{{/link-to}}
</div>
{{#each model as |rental|}}
<article class="listing">
<h3>{{rental.title}}</h3>
<div class="detail owner">
<span>Owner:</span> {{rental.owner}}
</div>
<div class="detail type">
<span>Type:</span> {{rental.type}}
</div>
<div class="detail location">
<span>Location:</span> {{rental.city}}
</div>
<div class="detail bedrooms">
<span>Number of bedrooms:</span> {{rental.bedrooms}}
</div>
</article>
{{/each}}
在这个模板中,我们循环了每一个模型对象,同时将其命名为 rental。对应每一个 rental,我们创建一个房屋信息的列表。
既然我们将展示租借信息,我们的验收测试验证通过时应该显示: