- Architecting Angular Applications with Redux,RxJS,and NgRx
- Christoffer Noring
- 318字
- 2021-08-27 19:56:20
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();