[AngularJS] Write a simple Redux store in AngularJS app
The first things we need to do is create a reducer:
/**
* CONSTANT
* @type {string}
*/
export const GET_CATEGORIES = "GET_CATEGORIES"; /**
* INIT VALUE
*/
export const initialCategories = [
{id: , name: 'Development'},
{id: , name: 'Design'},
{id: , name: 'Exercise'},
{id: , name: 'Humor'}
]; /**
* REDUCERS
* @type {string}
*/
export const categories = (state = initialCategories, {type, payload}) => {
switch(type) {
case GET_CATEGORIES:
return payload || state;
default:
return state;
}
};
It has some default initialize data. What it does is just simply return the state.
Then let's create a gloable store for the app, which has two methods, getState, dispatch. Two props: reducer, state.
class Store {
constructor(reducer, initialState) {
this.reducer = reducer;
this.state= initialState;
} getState() {
return this.state
} dispatch() {
this.state = this.reducer(this.state, action);
} }
Once we got that, we are going to init our store:
import {categories, initialCategories} from './components/categories/category.state';
import Store from './app.store';
const store = new Store(categories, initialCategories);
We passed in categoreis reudcer and the initialCategories state.
To make it available to Angular APP. we need to make it injectable:
let appModule = angular.module('app', [
CommonModule.name,
ComponentsModule.name
])
.value('store', store)
Then we can use it in our app:
class CategoriesController {
constructor(store) {
'ngInject'; angular.extend(this, {
store
});
} $onInit() {
this.store.dispatch({type: GET_CATEGORIES});
this.categories = this.store.getState();
}
}
Now we are going to simply the code a little bit, we going to make a subscribe method so that we don't need to call getState() method everytime after we dispatch an action.
You can think that the subscribe method is a just callback function which each time we dispatch an action, it will be called. And inside the callback function, we will call this.store.getState() to get the value.
class Store {
constructor(reducer, initialState) {
this.reducer = reducer;
this.state = initialState;
this.listeners = [];
} getState() {
return this.state;
} dispatch(action) {
this.state = this.reducer(this.state, action);
this.listeners.forEach((l) => l());
} subscribe(listener) {
this.listeners = [
...this.listeners,
listener
]; // return an unsubscribe function
return () => {
this.listeners = this.listeners.filter(l => l !== listener);
}
}
} export default Store;
class CategoriesController {
constructor($timeout, store) {
'ngInject'; angular.extend(this, {
$timeout,
store
});
} $onInit() {
this.unsubscribe = this.store.subscribe(() => {
this.categories = this.store.getState();
}); this.store.dispatch({type: GET_CATEGORIES});
}
}
Currently inside the dispatch() metod, we pass in an object with type and payload. It would be better if we can manage those action in a single place. There is where Action creator comes in to play.
/**
* ACTIONS CREATOR
*/
export const CategoriesActions = () => {
const getCategoreis = (categories) => {
return {type: GET_CATEGORIES, payload: categories}
}; const getCurrentCategory = (currentCategory) => {
return {type: GET_CURRENT_CATEGORY, payload: currentCategory}
}; return {
getCategoreis,
getCurrentCategory
};
};
To make it avaiable to Angular App, we can create a factory for this:
let appModule = angular.module('app', [
CommonModule.name,
ComponentsModule.name
])
.value('store', store)
.factory('CategoriesActions', CategoriesActions)
.component('app', AppComponent)
Then we can use it inside the controller:
constructor($timeout, store, CategoriesActions) {
'ngInject'; angular.extend(this, {
$timeout,
store,
CategoriesActions
});
}
$onInit() {
this.unsubscribe = this.store.subscribe(() => {
this.categories = this.store.getState();
}); this.store.dispatch(this.CategoriesActions.getCategoreis());
}
onCategorySelected(currentCategory) {
this.currentCategory = category(this.currentCategory, this.CategoriesActions.getCurrentCategory(currentCategory));
}
[AngularJS] Write a simple Redux store in AngularJS app的更多相关文章
- [后端人员耍前端系列]AngularJs篇:30分钟快速掌握AngularJs
一.前言 对于前端系列,自然少不了AngularJs的介绍了.在前面文章中,我们介绍了如何使用KnockoutJs来打造一个单页面程序,后面一篇文章将介绍如何使用AngularJs的开发一个单页面应用 ...
- Angularjs,WebAPI 搭建一个简易权限管理系统 —— Angularjs 前端主体结构(五)
目录 前言 Angularjs名词与概念 Angularjs 基本功能演示 系统业务与实现 WebAPI项目主体结构 Angularjs 前端主体结构 6 Angularjs 前端主体结构 6.1 A ...
- Angularjs,WebAPI 搭建一个简易权限管理系统 —— Angularjs名词与概念(一)
目录 前言 Angularjs名词与概念 Angularjs 基本功能演示 系统业务与实现 WebAPI项目主体结构 Angularjs 前端主体结构 2. 前言 Angularjs开发CRUD类型的 ...
- 【js类库AngularJs】web前端的mvc框架angularjs之hello world
AngularJS诞生于2009年,由Misko Hevery 等人创建,后为Google所收购.是一款优秀的前端JS框架,已经被用于Google的多款产品当中.AngularJS有着诸多特性,最为核 ...
- [Redux] Store Methods: getState(), dispatch(), and subscribe()
console.clear(); const counter = (state = 0, action) => { switch (action.type) { case 'INCREMENT' ...
- [Functional Programming ADT] Create a Redux Store for Use with a State ADT Based Reducer
With a well defined demarcation point between Redux and our State ADT based model, hooking up to a R ...
- [Redux-Observable && Unit Testing] Use tests to verify updates to the Redux store (rxjs scheduler)
In certain situations, you care more about the final state of the redux store than you do about the ...
- Simple Redux
This is a post that tries to explain the the basics of Redux. We’ll build a minimal working example ...
- iOS App Store上架新APP与更新APP版本
iOS App Store上架新APP与更新APP版本 http://www.jianshu.com/p/9e8d1edca148
随机推荐
- pidof---查找指定名称的进程的进程号id号。
pidof命令用于查找指定名称的进程的进程号id号. 语法 pidof(选项)(参数) 选项 -s:仅返回一个进程号: -c:仅显示具有相同“root”目录的进程: -x:显示由脚本开启的进程: -o ...
- 【习题 8-1 UVA - 1149】Bin Packing
[链接] 我是链接,点我呀:) [题意] 在这里输入题意 [题解] 每个背包只能装两个东西. 而且每个东西都要被装进去. 那么我们随意考虑某个物品.(不必要求顺序 这个物品肯定要放进某个背包里面的. ...
- Maven学习详解(13)——Maven常用命令大全与pom文件讲解
一.Maven常用命令 1.1.Maven 参数 -D 传入属性参数 -P 使用pom中指定的配置 -e 显示maven运行出错的信息 -o 离线执行命令,即不去远程仓库更新包 -X 显示ma ...
- JavaScript学习总结(9)——JS常用函数(一)
本文中,收集了一些比较常用的Javascript函数,希望对学习JS的朋友们有所帮助. 1. 字符串长度截取 ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 1 ...
- android:giavity和layout_gravity的差别
android:gravity: 是对该view中内容的限定.比方一个button 上面的text. 你能够设置该text 相对于view的靠左,靠右等位置. android:layout_gravi ...
- [C++11] 默认构造函数
类通过一个特殊的构造函数来控制默认初始化过程.这个函数就是默认构造函数.默认构造函数无需不论什么实參. 我们能够显示的定义默认构造函数也能够让编译器为我们生成默认构造函数. 默认构造函数以例如以下规则 ...
- 《深入理解java虚拟机》:类的初始化
深入理解java虚拟机>:类的初始化 类从被载入到虚拟机内存中開始.到卸载出内存为止,它的整个生命周期包含:载入.验证.准备.解析.初始化.使用和卸载七个阶段.当中验证.准备.解析3个部分统称为 ...
- ABAP调用外部WebService
TCode:se80 选择 Package,输入我们自己的开发包,后回车 右击 开发包名称,选择菜单 出现创建向导窗体 选择"Service Consumer",点击 继续 选择& ...
- Python-根据成绩分析是否继续深造
案例:该数据集的是一个关于每个学生成绩的数据集,接下来我们对该数据集进行分析,判断学生是否适合继续深造 数据集特征展示 GRE 成绩 (290 to 340) TOEFL 成绩(92 to 120) ...
- Spring中提供的集合工具类util CollectionUtils
转自:https://blog.csdn.net/fangwenzheng88/article/details/78457850 CollectionUtils类 /* * Copyright 200 ...