Ember 翻译——教程四:模型钩子

20 篇文章 0 订阅

模型钩子

现在,让我们在 index 模板添加一个可租借信息列表。我们知道,租借信息不会是静态的,因为用户最后需要能够添加、更新、删除它们。因为这个原因,我们需要一个租借信息模型来保存租借信息。简单起见,一开始我们将使用硬编码的 JavaScript 数组对象。稍后,我们将切换到使用 Ember Data,它是我们的 app 中一个强力的 数据管理库。

这会是我们主页已完成时候的样子:
image

在 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,我们创建一个房屋信息的列表。

既然我们将展示租借信息,我们的验收测试验证通过时应该显示:
image


原文地址

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值