Ember旅程系列(七)

编程入门 行业动态 更新时间:2024-10-07 10:19:17

Ember<a href=https://www.elefans.com/category/jswz/34/1729580.html style=旅程系列(七)"/>

Ember旅程系列(七)

英文原版:.13.0/tutorial/hbs-helper/

到目前为止,我们的应用展示的数据是从Ember data的model中获取的。随着应用变得日益复杂 ,我们可能会考虑在数据呈现给用户之前能够加以控制。出于这个原因,Ember提供了Handlerbars模版帮助我们用以对数据进行加工。现在让我们通过Handlerbars来帮助用户迅速的看到某个信息是属于 “standalone” 还是 “Community”。

生成rental-property-type助手。命令:

ember g helper rental-property-type

输出:

installing helpercreate app/helpers/rental-property-type.js
installing helper-testcreate tests/unit/helpers/rental-property-type-test.js

新生成的助手包含一些样板代码:

app/helpers/rental-property-type.jsimport Ember from 'ember';export function rentalPropertyType(params/*, hash*/) {return params;
}export default Ember.Helper.helper(rentalPropertyType);

好了,现在更新一下我们的rental-listing组件模版。在模版中加入我们刚刚创建的助手,并且给它传入参数rental.propertyType:

app/templates/components/rental-listing.hbs<article class="listing"><a {{action 'toggleImageSize'}} class="image {{if isWide "wide"}}"><img src="{{rental.image}}" alt=""><small>View Larger</small></a><h3>{{rental.title}}</h3><div class="detail owner"><span>Owner:</span> {{rental.owner}}</div><div class="detail type"><!--<span>Type:</span> {{rental.propertyType}} --><span>Type:</span> {{rental-property-type rental.propertyType}}- {{rental.propertyType}}</div><div class="detail location"><span>Location:</span> {{rental.city}}</div><div class="detail bedrooms"><span>Number of bedrooms:</span> {{rental.bedrooms}}</div>
</article>

理想状态下,我们应该会看到第一条信息包含”Type: Standalone - Estate” 字样。{{rental.propertyType}} 会返回rental.propertyType的值。 更新app/helpers/rental-property-type.js,让助手判断下,在其定义数组communityPropertyTypes内部是否包含rental.propertyType的值。并根据判断结果,返回 “Comunity” 或 “Standalone”:

app/helpers/rental-property-type.jsimport Ember from 'ember';const communityPropertyTypes = ['Condo','Townhouse','Apartment'
];export function rentalPropertyType([propertyType]) {if (communityPropertyTypes.includes(propertyType)) {return 'Community';}return 'Standalone';
}export default Ember.Helper.helper(rentalPropertyType);

在模版中传递给助手的参数都会被放入一个数组中,然后传递给助手。例如{{my-helper “foo” “bar”}} ,助手在接受参数的时候会以这种方式:myHelper([foo, bar])。(此处可阅读ES6 解构赋值)

跑起服务器,打开浏览器看一些效果吧。

本节完

更多推荐

Ember旅程系列(七)

本文发布于:2024-02-13 07:45:51,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1757649.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:旅程   系列   Ember

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!