我想在 Ember 中实现项目列表/项目详细信息模式,但细微差别是详细信息 View 必须出现在所选项目旁边。例如:
<ul>
<li><div>Post 1<div></li>
<li><div>Post 2<div></li>
<li><div>Post 3<div></li>
<li>
<div>Post 4<div>
<div>
<ul>
<li>Comment 1</li>
<li>Comment 2</li>
<li>Comment 3</li>
</ul>
</div>
</li>
<li><div>Post 5<div></li>
</ul>
我尝试过的 Handlebars 模板是:
<script type='text/x-handlebars' data-template-name='posts'>
<ul>
{{#each model}}
{{#linkTo 'post' this}}
<div>{{title}}</div>
{{/linkTo}}
{{#if isSelected}} <!-- How to implement isSelected ? -->
<div>{{!-- render selected post's comments --}}</div>
{{/if}}
{{/each}}
</ul>
</script>
我在 Controller 中尝试了这个:
App.PostController = Em.ObjectController.extend({
isSelected: function() {
return this.get('content.id') === /* what to put here? */;
}
});
我所困惑的是如何以“Ember”方式实现 isSelected
?我的方向正确吗?
最佳答案
您走在正确的道路上。诀窍是使用不同的 Controller 将产品包装在项目列表和项目详细信息中。因此,首先指定 Handlebars {{each}}
帮助器应将每个条目包装在 ListedProductController
{{#each model itemController="listedProduct"}}
现在定义 ListedProductController
,添加您一直在编写的 isSelected
函数。现在,它可以通过 needs
数组引用单例 ProductController
,将路由器设置的产品与列出的产品进行比较。
App.ProductController = Ember.ObjectController.extend({});
App.ListedProductController = Ember.ObjectController.extend({
needs: ['product'],
isSelected: function() {
return this.get('content.id') === this.get('controllers.product.id');
}.property('content.id', 'controllers.product.id')
});
我在这里发布了一个工作示例:http://jsbin.com/odobat/2/edit
关于ember.js - 如何从 Controller 或 View 获取路线的当前模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17587189/