gpt4 book ai didi

ember.js - 如何从 Controller 或 View 获取路由的当前模型?

转载 作者:行者123 更新时间:2023-12-02 06:05:13 26 4
gpt4 key购买 nike

我想在 Ember 中实现 item-list/item-detail 模式,但细微差别是细节 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? */;
}
});

我所困扰的是如何实现 isSelected以“ Ember ”方式?我是否朝着正确的方向前进?

最佳答案

你走在正确的轨道上。诀窍是使用不同的 Controller 将产品包装在 item-list 和 item-detail 中。因此,首先指定 Handlebars {{each}}助手应该将每个条目包装在 ListedProductController

{{#each model itemController="listedProduct"}}

现在定义 ListedProductController ,添加 isSelected你一直在写的函数。现在它可以引用单例 ProductController通过 needs数组,将路由器设置的产品与列出的产品进行比较。
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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com