Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ember.js: How to access nested view instances

Say I'm defining nested views, like so (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}}

I'd like to avoid binding a lot of attributes between the parent view and the child view. Rather, I'd like to do something like this.getPath('ChildView.foo'). But this.get('ChildView') returns the class that I created with Ember.View.extend, not the instance, so I cannot access the attributes.

Is there a canonical way to access the current instance of a child view from inside a method of the parent view?

like image 638
Jo Liss Avatar asked Apr 30 '12 20:04

Jo Liss


2 Answers

You can pass a view the viewName variable and access the view through the parent that way.

See http://jsfiddle.net/Tx3NP/5/

{{#view App.ParentView}}
  {{#view childView viewName="childViewInstance"}}
     ...
  {{/view}}
{{/view}}
console.log(this.get('childViewInstance.value'));

Or you can do as @weltraumpirat recommends and access the this.get('childViews') array.

like image 61
Bradley Priest Avatar answered Sep 24 '22 01:09

Bradley Priest


You can use the _childViews array:

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

or you can give your view an id and simply use jQuery to access the corresponding HTML element.

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

console.log( Em.$('#childView')[0].value );
like image 34
weltraumpirat Avatar answered Sep 24 '22 01:09

weltraumpirat