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

Cleaning up the view

The first order of business is to have a look at our first view and how it reacts to user interactions. It looks like this currently:

// first.view.js

import dispatcher from "./dispatcher";

class FirstView {
selectIndex(index) {
dispatcher.dispatch({
type: "SELECT_INDEX",
data: index
});
}
}

let view = new FirstView();

Adding a few more actions into the mix means we would extend the view with a few methods like this:

// first.viewII.js

import dispatcher from "./dispatcher";

class View {
selectIndex(data) {
dispatcher.dispatch({
type: "SELECT_INDEX",
data
});
}

createProduct(data) {
dispatcher.dispatch({
type: "CREATE_PRODUCT",
data
});
}

removeProduct(data) {
dispatcher.dispatch({
type: "REMOVE_PRODUCT",
data
});
}
}

let view = new View();

OK, so now we get how we can add actions. It looks a little ugly though with all these calls to the dispatcher and magic strings, so we clean this up a bit by creating a file with constants, called product.constants.js, which consists of the following code:

// product.constants.js

export const SELECT_INDEX = "SELECT_INDEX",
export const CREATE_PRODUCT = "CREATE_PRODUCT",
export const REMOVE_PRODUCT = "REMOVE_PRODUCT"

Let's do one more thing. Let's move the dispatcher into a product.actions.js; this is generally known as an action creator. This will contain the dispatcher and refer to our product.constants.js file. So let's create said file:

// product.actions.js

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

export const selectIndex = data =>
dispatcher.dispatch({
type: SELECT_INDEX,
data
});

export const createProduct = data =>
dispatcher.dispatch({
type: CREATE_PRODUCT,
data
});

export const removeProduct = data =>
dispatcher.dispatch({
type: REMOVE_PRODUCT,
data
});

With these constructs, we can clean up our view considerably to look like this:

// first.viewIII.js

import {
selectIndex,
createProduct,
removeProduct
} from 'product.actions';

function View() {
this.selectIndex = index => {
selectIndex(index);
};

this.createProduct = product => {
createProduct(product);
};

this.removeProduct = product => {
removeProduct(product)
};
}

var view = new View();
主站蜘蛛池模板: 许昌市| 峡江县| 高清| 马边| 衡山县| 化州市| 沅江市| 突泉县| 于都县| 潼关县| 原平市| 即墨市| 苏尼特右旗| 屯留县| 和硕县| 洞口县| 达州市| 鄂托克前旗| 中江县| 临安市| 荥经县| 汉阴县| 仁布县| 吉林市| 绍兴市| 凌源市| 朔州市| 子洲县| 壤塘县| 泸溪县| 湘潭市| 安庆市| 阜新市| 康保县| 中江县| 南靖县| 当涂县| 定日县| 呼图壁县| 类乌齐县| 东阳市|