[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
随机推荐
- AutoCAD 许可管理器不起作用,或未正确安装,现在将关闭
问题描述 重新安装了也还是这样,而且第二次打开都跳不出申请码界面就关闭了. 问题原因,初步认为:AutoCAD 在首次弹出申请激活类型的类型时,直接选择了网络激活,而且没有激活成功.再想通过激活码的方 ...
- Android模拟、实现、触发系统按键事件的方法
Android模拟.实现.触发系统按键事件的方法 /** * 模拟系统按键. * * @param keyCode */ public static void onKeyEvent(final ...
- Android启动原理剖析
我们知道Android是以一个Activity为单位的,可是我们并没有看到一个Activity是怎么開始启动的. 今天我 们就从Android的源码開始讲吧. ActivityThread: Andr ...
- 爬虫爬数据时,post数据乱码解决的方法
近期在写一个爬虫,目标站点是:http://zx.bjmemc.com.cn/.可能是为了防止被爬取数据,它给自身数据加了密. 用谷歌自带的抓包工具也不能捕获到数据. 于是下了Fiddler. ...
- AngularJS渲染性能分析
作者:Jiang, Jilin AngularJS中,通过数据绑定.能够十分方便的构建页面.可是当面对复杂的循环嵌套结构时,渲染会遇到性能瓶颈.今天,我们将通过一些列实验,来測试AngularJS的渲 ...
- 用 runcloud.io 免费部署、优化管理你的多个VPS( 目前支持 Ubuntu 16.04 )
使用RunCloud.io轻松实现Web部署 使用VPS.云服务器,通常会安装基本的操作系统,之后必须自己安装Apache,MySQL,PHP,尤其是服务器的性能优化,这对大多数人来说可能是非常具有挑 ...
- Funui-Theme 资源的替换
实现资源的替换,需要分为以下几个步骤 1.找到需要更改的模块 mediatek/packages/apps/FileManager 2.到主题模块下根据包名找到相应资源(以Grass为例) cd ve ...
- 35.Intellij IDEA设置忽略部分类编译错误
转自:https://www.aliyun.com/jiaocheng/290360.html 有些时候我们的项目中有些错误,但这些错误并不影响项目的整体运行(或许是没有使用到),默认情况下idea是 ...
- Zabbix监控Tomcat,Redis
一 Tomcat监控 1.1.1 Tomcat 端配置 JMX 编辑catalina.sh文件,配置如下: CATALINA_OPTS="$CATALINA_OPTS -Dcom.sun.m ...
- Codefroces 760 B. Frodo and pillows
B. Frodo and pillows time limit per test 1 second memory limit per test 256 megabytes input standard ...