jermainecraig
jermainecraig

Reputation: 311

Send actions to the Application controller in EmberJS

I'm trying to toggle a global property on the application controller, by clicking a button on one of the templates. I've read some stuff on action bubbling but can't it to work.

Here's the property and action on the Application controller

export default Ember.Controller.extend({
  isAuthenticated: true,
  actions: {
    logIn: function(){
      this.toggleProperty('isAuthenticated');
    }
  }
});

And here's the action with a login.hbs template file (I'll turn this into a proper button soon)

<span {{action 'logIn'}}>
    {{#link-to 'boards' class="btn-l bg-blue white db mtl link bn w-100"}}Login{{/link-to}}
</span> 

How could I ensure the action toggles the property on the Application Controller?

Upvotes: 3

Views: 1939

Answers (1)

Ember Freak
Ember Freak

Reputation: 12872

In your login controller,you need to inject application controller.

 import Ember from 'ember';

 export default Ember.Controller.extend({  
   appCont:Ember.inject.controller('application')
 });

and in login.hbs you need to specify which target will receive the method call.

<button {{action 'logIn' target=appCont}}> Login </button>

In this <button {{action 'logIn'}}> Login </button> , context of a template is login controller, actions used this way will bubble to login route when the login controller does not implement the specified action. Once an action hits a login route, it will bubble through the route hierarchy.

Reference: http://emberjs.com/api/classes/Ember.Templates.helpers.html#toc_specifying-a-target

EDIT: If you want to call functions available in Controller inside Component then you need to pass actions toComponent`

Login.hbs

{{component-a logIn=(action 'logIn') }}

component-a.hbs

<button {{action (action logIn)}}> LogIn</button>

Upvotes: 2

Related Questions