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

标签 ember.js

我想在 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/

相关文章:

javascript - Ember 根据参数名称返回未定义的 url 参数

Ember.JS insertNewLine 不起作用

Ember.js 新路由器 'history' 实现

javascript - 我应该在 View 中引用 controller.model 还是 controller.content?

javascript - Ember css 不起作用 + 如何创建两个样式表

javascript - 如何编写用于在 Ember.JS 中注册和注入(inject)的初始化程序?

ember.js - EmberJs是否支持发布/订阅者事件模式?

javascript - "Route was not found"Ember.js

javascript - 使环回 API 与 Ember.js 兼容

javascript - 设置不重定向的 Ember 根 URL