[英]Using a container view in ember.js - how to access parent variables from child view
I'm trying to access a parents view data from a container view, child view with no success. 我正在尝试从容器视图访问父视图数据,而没有成功访问子视图。
Here is a fiddler for it. 这是一个提琴手 。
What is the correct way to do this? 正确的方法是什么?
Using: ember-1.0.0-rc.1.js 使用:ember-1.0.0-rc.1.js
Javascript code: 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
});
and the template: 和模板:
<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>
Interesting what you are trying to do. 您想做的有趣。 But I did find a way to accomplish it.
但是我确实找到了实现它的方法。 Here is the Fiddle: http://jsfiddle.net/Sq2Dt/
这是小提琴: http : //jsfiddle.net/Sq2Dt/
You simply must climb the hierarchy of the views and then access the context like this: 您只需简单地爬升视图的层次结构,然后像这样访问上下文:
{{view.parentView.context.value}} and {{view.parentView.context.computed}}
It does seem kind of strange that the context of the Views inside the ContainerView is the ApplicationController while it's parents view's context is the MyController. 容器视图内部的视图上下文是ApplicationController,而其父视图的上下文是MyController,这似乎有些奇怪。 Go figure.
去搞清楚。
Hope that helps :) 希望有帮助:)
Yes, I was stumped on this too. 是的,我也为此感到困惑。 This thread helped me down the path, but in my case, this was the solution.
这个线程帮助我走了一条路,但就我而言,这就是解决方案。
// 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}
I'm not sure why sometimes, controller is used and other times, seemingly context to access it, but I figured I'd share how mine worked. 我不确定为什么有时会使用控制器,而有时却使用控制器,看似上下文来访问它,但我想我会分享我的工作方式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.