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

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);

}
});
主站蜘蛛池模板: 中阳县| 庆安县| 包头市| 蓝山县| 西畴县| 武定县| 汉寿县| 丹东市| 永年县| 建昌县| 台安县| 县级市| 疏勒县| 九寨沟县| 江北区| 黎城县| 甘泉县| 礼泉县| 华安县| 江源县| 金阳县| 固阳县| 长宁区| 平武县| 桃源县| 蕲春县| 德州市| 长垣县| 苏尼特右旗| 武隆县| 明水县| 拜城县| 东平县| 安陆市| 平远县| 衡阳县| 明水县| 叶城县| 桦南县| 桦甸市| 乐至县|