Understanding EventEmitters [for newbies]

I was trying to figure out how to use eventEmitters, be cause I forgot and I had no clue how to use them anymore. Then I came across this amazing video that shows you how its done.

this guy knows his stuff.

If you don’t want to watch the video or don’t have access to speakers, saving data… whatever, you can just follow along with me and my ways of explaining things to help me understand myself.

So I just want to explain it the best way i can understand it…so this won’t be textbook but it’ll probably just makes sense to me..ok enough disclaimers lets go.

Firstly you want to have an eventEmitter sample you can just go and clone this fella.

git clone https://github.com/tony2tones/eventEmitter-sample.git

There, now you have a project that has some eventEmitter action going down. It’s simple and it is a console log, but it’s the foundation to where we can start to understand whats happening.

Off the bat we can see that we will have a parent and child components to work with.

<app-component></app-component>
<header-component></header-component>

Let’s Navigate to the header component.

Now import Output, EventEmitter and a message to emit.

Maybe i’m going a bit slow, but it’ll pick up quickly i promise.

Now we can use those imports with making a new EventEmitter variable. This is very exciting and for the sake of speed you also added a function that emits the message…Oh also forgot an array of menu options.

Sweet, so we have made an emitterable variable called ‘messageBus’ which will “carry” the message string and emit it world wide.(within the boundaries of your angular project)

So we head on over to our Header view(html) and add the clickHandler function.

So thats officially in our header component…the parent component still doesn’t know anything about it just yet. There is one more step… ok there isn’t but we are close.

So how to we make it available? well you put it over here.

So we linkup that emitter variable called ‘messageBus’ to a function that can be found in our parent component.

Run that, check your console click on the nav and you’ll see the console responding with your emitted message all the way from the child component.