- Architecting Angular Applications with Redux,RxJS,and NgRx
- Christoffer Noring
- 252字
- 2021-08-27 19:56:20
Adding EventEmitter
The two last bullets can really be condensed into one theme, namely eventing, or the ability to register to and fire off events.
So what does a cleanup of the store look like, and why would we need to clean it up? The reason for cleaning it up is it makes for simpler code. There is a standard library that is often used when constructing a store, called EventEmitter. The library handles just what we mentioned previously, namely it is able to register and fire off events. It is a simple implementation of the pub-sub pattern. Basically, EventEmitter allows you to subscribe to certain events and also allows you to trigger events. For more information on the pattern itself, have a look at the following link: https://en.wikipedia.org/wiki/Publish%E2%80%93subscribe_pattern.
You could definitely write your own code for this, but it's nice to be able to use a dedicated library so you can focus on other things that matter, such as solving business problems.
We decided to use the EventEmitter library and we do so in the following way:
// store-event-emitter.js
export const Store = (() => {
const eventEmitter = new EventEmitter();
return {
addListener: listener => {
eventEmitter.on("changed", listener);
},
emitChange: () => {
eventEmitter.emit("changed");
},
getSelectedItem: () => store["selectedItem"]
};
})();
This makes our code a little cleaner because we no longer need to hold an internal list of subscribers. There are more changes we can make though, so let us talk about that in the next section.