Adding to and cleaning up the register method

One of the store's jobs has been to handle eventing, especially when the store wants to convey to a view that a change has happened to its state. In the store.js file, other things were happening as well, things like registering ourselves with the dispatcher and being able to receive dispatched actions. We used these actions to alter the state of the store. Let's remind ourselves what that looked like:

// store.js

let store = {};

function selectIndex(index) {
store["selectedIndex"] = index;
}

dispatcher.register(message => {
switch (message.type) {
case "SELECT_INDEX":
selectIndex(message.data);
break;
}
});

Here, we are only supporting one action, namely SELECT_INDEX. There are two things we need to do here:

  • Add the other two actions, CREATE_PRODUCT and REMOVE_PRODUCT, and the accompanying functions createProduct() and removeProduct()
  • Stop using magic strings and start using our constants file
  • Use the store we created in the store-event-emitter.js file

Let's implement the suggested changes from our preceding list:

// store-actions.js

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

let store = {};

function selectIndex(index) {
store["selectedIndex"] = index;
}

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

dispatcher.register(message => {
switch (message.type) {
case "SELECT_INDEX":
selectIndex(message.data);
break;
}
});

const createProduct = product => {
if (!store["products"]) {
store["products"] = [];
}

store["products"].push(product);
};


const 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);
break;
case CREATE_PRODUCT:
createProduct(data);

break;
case REMOVE_PRODUCT:
removeProduct(data);

}
});
..................Content has been hidden....................

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