2013-03-29 43 views
1

我試圖從容器視圖,子視圖訪問父視圖數據沒有成功。在ember.js中使用容器視圖 - 如何從子視圖訪問父變量

這是一個fiddler它。

這樣做的正確方法是什麼?

使用:燼-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 
}); 

和模板:

<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> 

回答

5

有趣的你正在嘗試做的。但我確實找到了一種方法來實現它。這裏是小提琴:http://jsfiddle.net/Sq2Dt/

你必須得爬意見的層次,然後訪問這樣的背景下:

{{view.parentView.context.value}} and {{view.parentView.context.computed}} 

它似乎有種奇怪的意見的ContainerView內的上下文ApplicationController雖然它的父視圖的上下文是MyController。去搞清楚。

希望可以幫到:)

+0

非常感謝,它確實有效!有沒有關於這方面的正式文件?你知道我如何訪問控制器方法嗎? – SimonW

2

是的,我也很難過。這個線程幫助我走上了這條路,但就我而言,這是解決方案。

// I use the #which command to preserve access to the outer context once inside the #each 
{{#with view as myOuterView}} 
    {{#each myInnerArray}} 
    //here, i get my 'name' property from the *controller* of myOuterView 
    {{myOuterView.controller.name}} 
    // stuff i did in inner array 
    {{/each} 
{{/with} 

我不知道爲什麼有時候,控制器使用等次,看似上下文來訪問它,但我想我會分享我是如何工作的。

相關問題