
Eventing with EventEmitter
Angular embraces reactive programming (also dubbed Rx-style programming) to support asynchronous operations with events. If you are hearing this term for the first time or don't have much idea about what reactive programming is, you're not alone.
Reactive programming is all about programming against asynchronous data streams. Such a stream is nothing but a sequence of ongoing events ordered based on the time they occur. We can imagine a stream as a pipe generating data (in some manner) and pushing it to one or more subscribers. Since these events are captured asynchronously by subscribers, they are called asynchronous data streams.
The data can be anything, ranging from browser/DOM element events to user input to loading remote data using AJAX. With Rx style, we consume this data uniformly.
In the Rx world, there are Observers and Observables, a concept derived from the very popular Observer design pattern. Observables are streams that emit data. Observers, on the other hand, subscribe to these events.
The EventEmitter class in Angular is primarily responsible for providing eventing support. It acts both as an observer and observable. We can fire events on it and it can also listen to events.
There are two functions available on EventEmitter that are of interest to us:
- emit: As the name suggests, use this function to raise events. It takes a single argument that is the event data. emit is the observable side.
- subscribe: Use this function to subscribe to the events raised by EventEmitter. subscribe is the observer side.
Let's do some event publishing and subscriptions to understand how the preceding functions work.