假设我正在定义嵌套视图,比如(code example on JSFiddle):
App.ParentView = Ember.View.extend({
ChildView: Ember.View.extend({ ... }),
method: function() {
this.get('ChildView') // => this is the class, not the instance :(
}
});
{{#view App.ParentView}}
{{#view ChildView}}
...
{{/view}}
{{/view}}
我希望避免在父视图和子视图之间绑定很多属性。相反,我想做一些像this.getPath('ChildView.foo')
这样的事情。但是this.get('ChildView')
返回我用Ember.View.extend创建的类,而不是实例,所以我不能访问属性。
有没有一种从父视图的方法内部访问子视图的当前实例的规范方法?
发布于 2012-05-01 15:39:34
您可以向视图传递viewName
变量,并以这种方式通过父视图访问该视图。
请参阅http://jsfiddle.net/Tx3NP/5/
{{#view App.ParentView}}
{{#view childView viewName="childViewInstance"}}
...
{{/view}}
{{/view}}
console.log(this.get('childViewInstance.value'));
或者,您也可以按照@weltraumpirat的建议进行操作并访问this.get('childViews')
阵列。
发布于 2016-12-23 20:58:21
这实际上很简单。
从2.10.0开始,如果您在一个组件中,并且需要查找一个嵌套的组件,那么只需搜索:
const id = 'my-specific-id-im-looking-for',
views = this.get('childViews');
let count = views.length;
if (count) {
while (--count) {
if (views[count].get('elementId') === id) {
// this is your view. do stuff with it, call methods on it, whatevs;
break;
}
}
}
如果您在此之前,请尝试使用组件的方法forEachChildView
https://stackoverflow.com/questions/10389947
复制相似问题