Search code examples
ember.jsember-octane

How to invoke an action in the current router from the child component in Ember Octane?


I am working with Ember Octane version, I want to invoke an action in the Route from the child component. The pseudo code is as follows.

**Route**
export default class SomeRouter extends Route {    
    model() {
        return data;        
    }
    @action
    refreshRoute() {
        this.refresh();
    }
}

**SomerRouter.hbs** 

<ChildComponent> //Using child component here

**ChildComponent**
export default class ChildComponent extends Component { 
    @action
    revert() {
       //How do I invoke the "refreshRoute" on the SomeRouter from here?
    }
}

In the revert method of the above child component, "this" refers to the component itself but in the previous version of the ember "this" refers to the router where I could simply call this.refresh(). So how do I achieve this in Ember Octane. Would really appreciate any help.


Solution

  • You dont. This is actually one of the things that are still a bit inconsistent even with octane. Because the bound context of the route template is the Controller, not the route. So you can not access the action with {{this.refreshRoute}}.

    To call an action on the Route your best way is to uzilize send. But to do this you need a Controller and define a different action on the Controller:

    controllers/some.js:

    export default class SomeController extends Controller {
      @action
      refreshRouteFromController() {
        this.send('refreshRoute');
      }
    }
    

    Now this function you can use from your template:

    <ChildComponent @refresh={{this.refreshRouteFromController}}>
    

    And then use it from your component:

    revert() {
       this.args.refresh();
    }
    

    Or directly from a button:

    <button {{on "click @refresh}}>...</button>