在Ember.js的模板中,当您在#each块中时,您如何引用父上下文中的值?

前端之家收集整理的这篇文章主要介绍了在Ember.js的模板中,当您在#each块中时,您如何引用父上下文中的值?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个模板中的情况,我想在每个块内的父上下文中使用if块.

代码

App = Ember.Application.create({});

App.view = Ember.View.extend({
    foo: [1,2,3],bar: true
});

模板:

<script type="text/x-handlebars">
{{#view App.view}}
    {{#each foo}}
        {{#if bar}}
            {{this}}
        {{/if}}
    {{/each}}
{{/view}}
</script>

这不起作用,因为在每个循环内引用的名称被限定为迭代元素.你如何引用父上下文中的东西?

演示:http://jsfiddle.net/hekevintran/sMeyC/1/

解决方法

我找到了一个更好的解决方案.

从Ember.js视图层指南(http://emberjs.com/guides/understanding-ember/the-view-layer/):

Handlebars helpers in Ember may also specify variables. For example,the {{#with controller.person as tom}} form specifies a tom variable that descendent scopes can access. Even if a child context has a tom property,the tom variable will supersede it.

This form has one major benefit: it allows you to shorten long paths without losing access to the parent scope.

It is especially important in the {{#each}} helper,which provides a {{#each person in people}} form. In this form,descendent context have access to the person variable,but remain in the same scope as where the template invoked the each.

模板:

<script type="text/x-handlebars" >
    {{#view App.view}}
        {{#each number in view.foo}}
            {{#if view.bar}}
                {{number}}
            {{/if}}
        {{/each}}
    {{/view}}
</script>​

演示:http://jsfiddle.net/hekevintran/hpcJv/1/

猜你在找的JavaScript相关文章