Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

binding controller object to a component in ember

Tags:

ember.js

I am trying to build a modal box component in ember. The modal box has two standard buttons, "close" and "save". I wanted to pass controller action to this component so that when save button is clicked, it calls the controller action that was passed. I call my component as :

 {{#affi-modal-box title="Test title" modalId="createNewAnalyticsRunModal" controllerBinding=controller}}some message{{/affi-modal-box}}

and my component :

AS.AffiModalBoxComponent = Ember.Component.extend({
attributeBindings: ['modelId','test'],
    //this is the function that gets called when save button is clicked 
    onSaveButtonClick : function(){

        console.log(this.controllerFor('analysisTemplates'));//fails
        console.log(this.get('controller'));//returns modal box component which I don't need 
    }

});

Any ideas how I can pass the controller object to the component??

Thanks.

like image 819
Deewendra Shrestha Avatar asked Sep 27 '13 19:09

Deewendra Shrestha


1 Answers

The way Ember.Component's work is to be agnostic to other parts of your application, therefore rather then passing in a controller on which you want an action to be called on when something happens in your component, you do it more like in this way:

{{#affi-modal-box 
  title="Test title" 
  modalId="createNewAnalyticsRunModal" 
  action="actionNameOnTheController"}}some message{{/affi-modal-box}}

As you can see you set the action attribute to the action name on your controller, and then inside your component you simply call this.sendAction('action'); which will trigger whatever action name you defined earlier:

AS.AffiModalBoxComponent = Ember.Component.extend({
  attributeBindings: ['modelId','test'],
  //this is the function that gets called when save button is clicked 
  onSaveButtonClick : function(){
    this.sendAction('action');
  }
});

So now, whenever onSaveButtonClick is invoked it will send the action actionNameOnTheController to whatever controller is listening to it. And best of all, without knowing nothing about the controller. This is the kind of functionality that makes Ember.Component's reusable in any way.

Please see here a simple demo of the concept explained.

Hope it helps.

like image 70
intuitivepixel Avatar answered Oct 21 '22 23:10

intuitivepixel