旅程系列(七)"/>
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旅程系列(七)
发布评论