官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 岑巩县| 睢宁县| 灵璧县| 黄陵县| 泽普县| 峨眉山市| 建水县| 阿勒泰市| 满城县| 财经| 开平市| 武汉市| 寿阳县| 万山特区| 富裕县| 牟定县| 玛曲县| 弋阳县| 庆阳市| 双鸭山市| 子洲县| 普洱| 长子县| 特克斯县| 即墨市| 随州市| 偏关县| 微博| 长春市| 龙泉市| 茌平县| 台山市| 桦甸市| 黑山县| 比如县| 伊宁市| 栖霞市| 鄂托克前旗| 海原县| 五家渠市| 和硕县|