0
votes

In my Ember app I have a model, which is an array loaded from backend. Each item describes a widget. Each widget type is represented by Ember component. User puts input in each widget and now all the widgets needs to be evalueated at once (after pressing a button, which is located outside of all components).

How to achieve that? I thought I could use ember-component-inbound-actions and send an action to each component, however I don't know, how to bind arbitrary number of widgets to arbitrary number of controller properties (strings don't work).

1

1 Answers

2
votes

You could create Ember.Service which emits event, inject it into route or controller (place from where you send action when user clicks button) and all components. Then, you should subscribe in your components to event emitted from Ember.Service, or, if it is shared logic, you could create Mixin with specific method and use it in all components, and react to that action emitted from controller.

Example service:

export default Ember.Service.extend(Ember.Evented, {  
    emitButtonClicked() {
        this.trigger('buttonClicked');
    }
});

Example component:

export default Ember.Component.extend({
  theService: Ember.inject.service('theservice'),

  doSomethingWithInput() {
    this.set('randomProperty', true);
    console.log('Do something with input value: ' + this.get('inputVal'));
  },

  subscribeToService: Ember.on('init', function() {
    this.get('theService').on('buttonClicked', this,  this.doSomethingWithInput);
  }),

  unsubscribeToService: Ember.on('willDestroyElement', function () {
    this.get('theService').off('buttonClicked', this, this.doSomethingWithInput);
  })

});

Example controller:

export default Ember.Controller.extend({
  theService: Ember.inject.service('theservice'),
  actions: {
    buttonClicked() {
        this.get('theService').emitButtonClicked();
    }
  }
});

And example template:

<button {{action 'buttonClicked'}}>Global Button</button>

First component:
{{my-component}}

Second component:
{{my-component}}