Broadcasting Events from one component to another


#1

Hello, can I broadcast an event from a view/component which I can listen to anywhere?

In my case, I want to trigger an event on a view and then listen to it on every component that has been added. I added a jquery handler on the body and capturing that event whenever triggered on each component, but is there a better way of doing it by banking on the Ember.Evented mixin’s trigger method?


#2

If I understood you correctly, when triggering an event, you can save updated state in your component controller.

Then observe your controller variable ('controllers.yourcomponentcontroller.state') from another controller you wish to update.


#3

What muchweb said is correct if all you need to do is observe state that changed because of some other component’s action. However, I can see how that wouldn’t be enough, so I offer this alternative:

I’m afraid that emitting actions from your controller that the component listens to isn’t easy. Making a view listen is relatively easy:

App.ListeningView = Ember.View.extend({
    didInsertElement: function () {
        this.get('controller').on('emittedAction', function () {
            // do stuff
        });
    }
});

App.SomeController = Ember.Controller.extend(Ember.Evented, {
    actions: {
        'emittedAction': function () {
            this.trigger('emittedAction');
        }
    }
});

Do you see why this wouldn’t work for components? Components have no way of getting at their controller to register .on('emittedAction').

Docs about this.


#4

Yes and that is why I was asking this question. Since i wanted to write a standalone component, I wanted to capture an ‘escape’ event outside the component, with the user only needing to just trigger an event. This is why i wanted to capture it inside a component.


#5

Gotcha. Sorry to say I don’t know of a good method in that case. It’s possible that the creators of the components didn’t intend for them to easily listen to events, so a hack might be needed.


#6

It seems to me you could just pass in a source of events when you define the component.

{{x-component listenTo=controller}}

And the opposite of course being:

{{x-component broadcastTo=controller}}

And then you just use those properties inside the component to listen to or trigger events.


#7

Is there any documentation for this? I could not find it anywhere.


#8

There’s documentation for using events in ember here: http://emberjs.com/api/classes/Ember.Evented.html

listenTo and broadcastTo are just names of properties; they don’t do anything by default in components.