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();
}
});
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset