[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
随机推荐
- widget-移除底部小部件内容
今天有一个要求,就是在调出手机窗口小部件的时候,让其中的某些小部件不显示.折腾了好久,虽然不知道原理,最终还是实现了屏蔽其中个别小部件的方法.记录下来 要想屏蔽底部小部件的显示,只需要把相关的类跟广播 ...
- STL中向量vector笔记
vector的本质是:数组的封装 特点:读取能在常数时间内完成 Vector成员函数 函数 表述 c.assign(beg,end) c.assign(n,elem) 将[beg; end)区间中的数 ...
- 轻松学习Linux之本地安装系统
1.安装Linux前的准备工作(详细讲解了系统分区,及类型) 2.轻松学习Linux之用光驱安装 3.轻松学习Linux之用光驱安装(之二) 4.硬盘安装Linux系统 本文出自 "李晨光原 ...
- scrapy爬取知乎某个问题下的所有图片
前言: 1.仅仅是想下载图片,别人上传的图片也是没有版权的,下载来可以自己欣赏做手机背景但不商用 2.由于爬虫周期的问题,这个代码写于2019.02.13 1.关于知乎爬虫 网上能访问到的理论上都能爬 ...
- codeforces 204E. Little Elephant and Strings(广义后缀自动机,Parent树)
传送门在这里. 大意: 给一堆字符串,询问每个字符串有多少子串在所有字符串中出现K次以上. 解题思路: 这种子串问题一定要见后缀自动机Parent树Dfs序统计出现次数都是套路了吧. 这道题统计子串个 ...
- django 简单会议室预约(5)
再来看看views.py的后半部分,对数据库的增删改查 #获取学院列表 def get_acad_list(): room_list = ConfeRoom.objects.all() #对数据库的操 ...
- 百度地图API 添加标签
1.手动创建数据,实际项目则是接受GPS信息 /建立坐标点: // lng:经度 lat:纬度 var points = [ {"lng":112.58,"lat&quo ...
- Vue 学习记录<1>
1.环境搭建:(前提node.js搭建) # 全局安装 vue-cli $ npm install --global vue-cli # 创建一个基于 webpack 模板的新项目 $ vue i ...
- HDU 1848(sg博弈) Fibonacci again and again
Fibonacci again and again Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Jav ...
- Android时间对话框TimePickerDialog介绍
目前网上流行着很多对“时间对话框TimePickerDialog”的讲解文章,但感觉都不是很详细.这里详细对该方面的知识进行介绍,旨在帮助初学者能够快速掌握该项技术. 首先要做的是声明一个日历类的对象 ...