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

Further improvements

There are definitely more improvements we can make to this code. We did use ES2015 imports to import other files, but most of our code was written in ES5 so why not use most of what ES2015 gives us? Another improvement we can make is introducing immutability and making sure our store is not mutated but transitions from one state to another. 

Let's have a look at the store file, primarily because that is where we can add the most ES2015 syntax. Our revealing module pattern looks like this currently:

// store-event-emitter.js

var Store = (function(){
const eventEmitter = new EventEmitter();

return {
addListener: listener => {
eventEmitter.on("changed", listener);
},
emitChange: () => {
eventEmitter.emit("changed");
},
getSelectedItem: () => store["selectedItem"]
};
})();

It can be replaced with a simple class and instead of instantiating an EventEmitter, we can inherit from it. In all fairness, we could have used ES2015 inheritance or the merge library to not have to create a separate EventEmitter instance, but this shows how elegant ES2015 can make things:

// store-es2015.js

import { EventEmitter } from "events";
import {
SELECT_INDEX,
CREATE_PRODUCT,
REMOVE_PRODUCT
} from "./product.constants";

let store = {};

class Store extends EventEmitter {
constructor() {}
addListener(listener) {

this.on("changed", listener);
}


emitChange() {
this.emit("changed");
}


getSelectedItem() {
return store["selectedItem"];
}

}

const storeInstance = new Store();

function createProduct(product) {
if (!store["products"]) {
store["products"] = [];
}
store["products"].push(product);
}

function removeProduct(product) {
var index = store["products"].indexOf(product);
if (index !== -1) {
store["products"].splice(index, 1);
}
}

dispatcher.register(({ type, data }) => {
switch (type) {
case SELECT_INDEX:
selectIndex(data);
storeInstance.emitChange();
break;
case CREATE_PRODUCT:
createProduct(data);
storeInstance.emitChange();
break;
case REMOVE_PRODUCT:
removeProduct(data);
storeInstance.emitChange();
}
});
主站蜘蛛池模板: 林甸县| 松潘县| 库尔勒市| 中阳县| 临漳县| 龙井市| 石河子市| 楚雄市| 莱阳市| 阳原县| 都江堰市| 临武县| 安远县| 桦甸市| 巧家县| 富裕县| 邯郸市| 甘洛县| 麦盖提县| 南召县| 讷河市| 宽城| 兖州市| 米脂县| 浮山县| 齐齐哈尔市| 安龙县| 洞头县| 扎兰屯市| 项城市| 炎陵县| 太白县| 庆安县| 绩溪县| 化州市| 大渡口区| 五原县| 天峻县| 潼关县| 千阳县| 洛扎县|