Ember component send action to route

前端 未结 2 1782
无人及你
无人及你 2020-11-27 19:29

I have two component and one sitting on another. I need to send an event to main route from child component( both components use in same route)

Please let m

2条回答
  •  青春惊慌失措
    2020-11-27 20:04

    Starting with Ember 3.14, Octane, we can solve this problem in a modern, explicit, concise and clear way -- which we'll get to after this brief intermission:

    I need to send an event to main route from child component

    While this is possible, it's strongly recommended against, as Routes should not have actions and should be stateless. That said, we can solve the problem of action passing through deep components in a couple of ways:

    • "Data Down, Actions Up"
    • Use a Service

    For the first, Data Down, Actions Up, you may pass arguments down as many component layers as you desire

    // app/controllers/application.js:
    @action
    dance(){
      console.log('┏(-_-)┓┏(-_-)┛┗(-_- )┓')
    }
    
    // app/templates/application.hbs
    
    
    // app/components/foo.hbs
    
    
    // app/components/bar.hbs
    
    

    This could be a slipperly slope. While only having two components to data down, and to action back up (after a click in this case), it may not seem like too much effort, but many UIs could be 10+ components deep, and would lend themselves to an anti-pattern known as Prop-Drilling.

    To mitigate prop-drilling, we have another approach in our toolbox to reach for. Services!

    // app/services/my-service.js
    @action
    dance(){
      console.log('┏(-_-)┓┏(-_-)┛┗(-_- )┓')
    }
    
    // app/components/bar.js
    import Component from '@glimmer/component';
    import { inject as service } from '@ember/service';
    
    export default class Bar extends Component {
      @service myService;
    }
    
    // app/components/bar.hbs
      
    

    The deeply nested component can access the action directly, rather than needing to be passed through a few layers -- this leads to much more maintainable and clear code.

    Resources

    • Classic to Octane Cheat Sheet
    • Octane Edition Documentation Page

提交回复
热议问题