blueFast
blueFast

Reputation: 44351

How to access controller in didInsertElement

I have a bootstrap dropdown which I need to activate once it has been inserted in the DOM. The view/controller is not associated to a route: it is just a component of my navigation bar. I configure the element id in the controller:

App.DropdownController = Ember.ObjectController.extend({
    elId : 'my-element-id',
});

So that I can use it in the template:

<a class="dropdown-toggle opener" {{bind-attr id="elId"}} data-toggle="dropdown">
    <i class="icon-off icon-2x"></i>
</a>
...

But in didInsertElement I have to hack my way to get the controller:

App.DropdownView = Ember.View.extend({
    templateName: 'navbar/dropdown',
    didInsertElement: function() {
        var controller = App.__container__.lookup('controller:dropdown'); // TODO: how to properly get controller?
        var elId = controller.get('elId');
        $('#' + elId).dropdown();
    }
});

How do I properly access the controller in the view?

Upvotes: 1

Views: 376

Answers (2)

Miguel Madero
Miguel Madero

Reputation: 1948

You could use this.get('controller'), however, in general it's better not to access the controller directly. My preference is to either push them or create a dependency. To push set them in markup that way the view defines its dependencies and they're passed in, as opposed to pulled.

{{view elId=eldId}}

Another option is to create a derived property.

App.DropdownView = Ember.View.extend({
  elId: function () { return this.get('controller.elid') }.property('controller.elid');
  didInsertElement: function() {
    $('#' + this.get('elId')).dropdown();
  }
});

The option looks similar to pulling, but having the derived property, removes the knowledge of where the property is coming from, from the place it's needed.

Upvotes: 0

maheshsenni
maheshsenni

Reputation: 782

You can use the view's controller property to access the controller. Using this property, you can access it in the didInsertElement handler like this.

var controller = this.get('controller');

Upvotes: 2

Related Questions