在ember.js中使用容器视图 - 如何从子视图访问父变量

Sim*_*onW 1 javascript ember.js

我正在尝试从容器视图访问父视图数据,子视图没有成功.

这是一个小提琴手.

这样做的正确方法是什么?

使用:ember-1.0.0-rc.1.js

Javascript代码:

App = Ember.Application.create({
    rootElement: '#app',
    name: 'My app',
    ready: function(){
        console.log('ready');
    },
});

App.mod = Ember.Object.extend({
    value: null,

    computed: function(value) {
        return 'computed';
    }.property()
});

App.MyController = Ember.ArrayController.create({
    content: [],
    init: function(){
        // create an instance of the model
        var item = App.mod.create({
            value: 'somevalue'
        });
        this.pushObject(item);
    }
});

App.SecondView = Ember.View.extend({
    tagName: 'span',
    classNames: ['second'],
    template: Ember.Handlebars.compile("second view with values: '{{value}}' & '{{computed}}'"),
});

App.FirstView = Ember.View.extend({
    tagName: 'span',
    classNames: ['first'],
    template: Ember.Handlebars.compile("first view"),
});

App.ViewsContainer = Ember.ContainerView.create({
    tagName: 'span',
    classNames: ['Container'],
    childViews: ['first_v', 'second_v'],
    first_v: App.FirstView,
    second_v: App.SecondView
});
Run Code Online (Sandbox Code Playgroud)

和模板:

<div id="app">
    <script type="text/x-handlebars">
        Test <b>{{App.name}}</b><br><br>
        {{#each App.MyController.content}}
               this should be printed: "{{value}}" & "{{computed}}"<br><br>
            {{view App.ViewsContainer}}
        {{/each}}
    </script>
</div>
Run Code Online (Sandbox Code Playgroud)

小智 5

有趣的是你想​​做什么.但我确实找到了实现它的方法.这是小提琴:http://jsfiddle.net/Sq2Dt/

您只需爬上视图的层次结构,然后访问上下文,如下所示:

{{view.parentView.context.value}} and {{view.parentView.context.computed}}
Run Code Online (Sandbox Code Playgroud)

ContainerView中的Views的上下文是ApplicationController,而它的父视图的上下文是MyController,这似乎有点奇怪.去搞清楚.

希望有帮助:)