Ember.js:如何访问嵌套视图实例

时间:2012-04-30 20:11:04

标签: javascript ember.js

假设我正在定义嵌套视图,如此(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创建的类,而不是实例,因此我无法访问属性。

是否有一种规范方法可以从父视图的方法内部访问子视图的当前实例?

3 个答案:

答案 0 :(得分:24)

您可以传递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')数组。

答案 1 :(得分:2)

您可以使用_childViews数组:

 console.log( this._childViews[0].get('value') );

您可以为视图提供ID,只需使用jQuery即可访问相应的HTML元素。

{{#view childView id="childView"}}

console.log( Em.$('#childView')[0].value );

答案 2 :(得分:0)

实际上很简单。

从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