您可以在车把模板中为account 定义属性绑定。
此绑定的工作方式如下:
<script type="text/x-handlebars">
<h1>App</h1>
{{#each item in controller}}
{{#view App.AccountView accountBinding="item"}}
<a {{bindAttr href="view.account.url"}} target="_blank">
{{view.account.name}}
</a>
{{/view}}
{{/each}}
</script>
注意我加了accountBinding,所以一般规则是propertyName和Binding作为后缀。请记住,当您向视图添加属性时,您将无法直接访问它,而是必须使用view.propertyName 访问它,如上所示。
请记住,在使用 {{view}} 助手时,您必须有一个 View 类:
window.App = Em.Application.create();
App.AccountView = Em.View.extend(); // this must exist
App.ApplicationRoute = Em.Route.extend({
model: function() {
return [
{id: 1, name: 'Ember.js', url: 'http://emberjs.com'},
{id: 2, name: 'Toronto Ember.js', url: 'http://torontoemberjs.com'},
{id: 3, name: 'JS Fiddle', url: 'http://jsfiddle.com'}];
}
})
工作小提琴:http://jsfiddle.net/schawaska/PFxHx/
响应更新 1:
我发现自己处于类似情况,最终创建了一个子视图来模仿 {{linkTo}} 助手。我真的不知道/认为这是最好的实现。
你可以在这里看到我之前的代码:http://jsfiddle.net/schawaska/SqhJB/
当时我已经在ApplicationView: 中创建了一个子视图:
App.ApplicationView = Em.View.extend({
templateName: 'application',
NavbarView: Em.View.extend({
init: function() {
this._super();
this.set('controller', this.get('parentView.controller').controllerFor('navbar'))
},
selectedRouteName: 'home',
gotoRoute: function(e) {
this.set('selectedRouteName', e.routeName);
this.get('controller.target.router').transitionTo(e.routePath);
},
templateName: 'navbar',
MenuItemView: Em.View.extend({
templateName:'menu-item',
tagName: 'li',
classNameBindings: 'IsActive:active'.w(),
IsActive: function() {
return this.get('item.routeName') === this.get('parentView.selectedRouteName');
}.property('item', 'parentView.selectedRouteName')
})
})
});
我的把手看起来像这样:
<script type="text/x-handlebars" data-template-name="menu-item">
<a {{action gotoRoute item on="click" target="view.parentView"}}>
{{item.displayText}}
</a>
</script>
<script type="text/x-handlebars" data-template-name="navbar">
<ul class="left">
{{#each item in controller}}
{{view view.MenuItemView itemBinding="item"}}
{{/each}}
</ul>
</script>
很抱歉,我不能给你更好的答案。这是我当时能想到的,从那以后就再也没有碰过。就像我说的,我不认为这是处理它的方法。如果您愿意查看{{linkTo}} helper source code,您将看到一个模块化且优雅的实现,它可能是您自己实现的基础。我猜你正在寻找的部分是 href 属性,它的定义如下:
var LinkView = Em.View.extend({
...
attributeBindings: ['href', 'title'],
...
href: Ember.computed(function() {
var router = this.get('router');
return router.generate.apply(router, args(this, router));
})
...
});
所以我想,从那里您可以了解它的工作原理并自行实现某些东西。让我知道这是否有帮助。