简体   繁体   中英

Ember send action from one component to other

In my Ember app, I have a parent component my-section.hbs defined as below;

{{#my-scale}}
{{my-field}}
{{/my-scale}}

Now in my-field, I have

{{my-textfield label=fldName key-up="onFieldChange"}}

My question is how do I get access to onFieldChange in my-scale component?

I would approach this problem by having my-scale provide the action that my-field will invoke. You can do this through a Closure Action

Since a "block" component (like my-scale can provide variables to its block (where my-field is) you can yield the action to call on key-up

// my-field.hbs
{{yield (action 'some-action-to-invoke-on-key-up')}}

and then pass it into the field

{{#my-scale as |someAction|}}
  {{my-field action=(action someAction)}}
{{/my-scale}}

which you can then bind to the key-up event

{{my-textfield label=fldName key-up=(action someAction)}}

This is IMO a bit easier than bubbling regular actions; you can pass the function around as a function instead, and just call it like a regular function (or bind it to an event)

I put together a little demo so you can see it in action here .

You need to use sendAction() at each layer you want to bubble up. So, in this case, you need to bubble up twice to go from myTextfield to myField to myScale .

// templates/my-section.hbs
  {{#my-scale}}
  {{my-field}}
  {{/my-scale}}

// component/myTextfield.js
export default Ember.Component.extend({
  actions: {
    onFieldChange() {
      this.sendAction('onFieldChange');
    }
  }
});

// component/myField.js
export default Ember.Component.extend({
  actions: {
    onFieldChange() {
      this.sendAction('onFieldChange');
    }
  }

// component/myScale.js
export default Ember.Component.extend({
  actions: {
    onFieldChange() {
      // do something
    }
  }
});

Alternatively, consider using something like ember-route-action-helper and specifying your actions on the route.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM