How can I call an event from my controller to my component


#1

Hi All,

Running into an issue that I’ve been stuck on for days and I can’t seem to figure this out. It seems like it would be simple enough but apparently it isn’t. I have an action in my controller:

…controllers/car-detail.js … actions: { callComponent(){ //want to call the fromController() function inside of my component } }

…/components/car-detail.js My Component fromController(){ //something needs to happen in here }

References: http://stackoverflow.com/questions/27802508/ember-js-component-observer-does-not-work http://stackoverflow.com/questions/19618604/how-to-call-method-of-a-component-from-a-controller http://stackoverflow.com/questions/22861316/calling-a-controllers-method-in-another-controller-ember

Can someone lend a hand with this one?


#2

Why not just handle the action in your component and send it back up to the controller?: https://guides.emberjs.com/v2.4.0/components/triggering-changes-with-actions/


#3

Thanks for the response. I’d be ok with that, but the problem is, I need to call a function inside of the component when the component is not actually used, so I can’t really handle the action inside of the component. If i put:

actions: {
        callComponent() { 
          //want to call the fromController() function inside of my component 
        }

Inside of my component, the callComponent() method will never get fired. The action is being sent by through another controller.


#4

Sounds like you’ll need to use a service. The question is does the fromController() method need to change something in the display that a computed property on the service could trigger within the component? (For example inject the service into the component and within the component make a computed property off of something within the service. Then the controller action can just grab the service and manipulate it to cause the computed property to change)

If not and you literally just need a method executed within the component then using http://emberjs.com/api/classes/Ember.Evented.html within the service could give you the mechanism you are looking for. So within the controller you could do:

carThing: Ember.service.inject(),
actions: {
  callComponent() {
    this.get('carThing').triggerEventMethod()
  }
}

The car thing service would be something like this code sample, extending Evented which would let the triggerEventMethod() call trigger('someEvent') which the component could be listening for and react to.

Hope that helps!


#5

if you do not need a eventbus in general you can add this to your component

didReceiveAttrs: function() { this.set(‘targetObject.’ + this.get(‘register-as’), this); },

and then you can call your component from controller with prvidet name from register-as attr.

but keep in mind normaly the rule is ddau.