17

This is probably beyond easy, but I'm having a hard time to figure out how to access properties of parent views:

App.ParentView = Ember.View.extend({
  foo: 'bar',

  child_view: Ember.View.extend({

    init: function(){
       // get the value of App.ParentView.foo
       //  ???
    }
  })

});
Panagiotis Panagi
  • 9,927
  • 7
  • 55
  • 103
  • Please note that in many cases accessing the parent view is a sign of code smell. However, it's hard to say more without knowing details here. – Peter Wagenet Feb 19 '14 at 19:29

3 Answers3

30

To get the view: this.get('parentView')

To get the value of foo this.get('parentView.foo')

Peter Wagenet
  • 4,976
  • 22
  • 26
Tom Whatmore
  • 1,327
  • 9
  • 11
  • 1
    Given a situation where you want to access the parent view in handlebars, you can use `{{view.parentView.foo}}`. ie: `{{#view Wrapper}}
    {{view.parentView.foo}}
    {{/view}}`
    – chuckg Aug 15 '13 at 00:40
  • 2
    Newbies heads up! The code above here says App.parentView wich is misleading. You should always get("parentView") regardless to the name you have given your view. – Nico Nov 28 '13 at 00:06
  • Thanks for this. Just saved me a lot of time. – Dexter Jun 06 '14 at 03:47
4

In Ember before 1.0.pre you could also use getPath method, instead of chains of get(), for more succinct (and generally safer) code:

this.getPath("parentView.foo");

What's cool in Ember 1.0.pre is that get() method now supports paths, so you can write

this.get("parentView.foo");
tokarev
  • 2,575
  • 1
  • 21
  • 26
3

Tom is correct. I also created a JS Fiddle to demonstrate this and also illustrate the special contentView property, which can be useful in this type of situation: http://jsfiddle.net/rSLQK/2/

Luke Melia
  • 8,389
  • 33
  • 41