出发点:之前起点小程序尝试mpvue的一个重要原因就是mpvue支持状态管理,虽然现在wepy也支持了redux,但是其性能不是非常理想,且看到issue里面还是提了很多的bug,所以还是想着用原生来撸一个简单够用的。

Pub/Sub模式(发布/订阅模式)

状态管理中非常重要的点就是发布/订阅模式,发布/订阅模式的原理非常简单,一边发布,一边订阅。订阅者在事件中心注册具名事件和回调函数,发布者通知事件中心执行所有同名的回调函数。

1
订阅者 ---- 注册事件 ----> 事件中心 <---- 通知 ---- 订阅者

事件中心(pubsub.js)

既然需要提供事件注册(订阅)的功能,那么必然需要一个地方来存放所有的事件,同一个事件名可以有多个回调,那么显然数据结构如下:

1
2
3
4
{
'fn_name': [fn1, fn2, fn3...],
...
}

所以事件中心的雏型如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
export default class PubSub {
constructor() {
// events里存放的是所有的具名事件
this.events = {};
}

// 提供订阅功能
subscribe(event, callback) {
...
}

// 提供发布功能
publish(event, data) {
...
}
}

订阅功能:在具名事件的回调数组中推入了一个新的回调,接受一个事件名和回调函数。

1
2
3
4
5
6
7
8
9
subscribe(event, callback) {
let self = this;

if(!self.events.hasOwnProperty(event)) {
self.events[event] = [];
}
// 没有做去重
return self.events[event].push(callback);
}

发布功能:调用对应事件名的所有回调函数,参数为事件名和回调参数。

1
2
3
4
5
6
7
8
9
10
publish(event, data = {}) {

let self = this;

if(!self.events.hasOwnProperty(event)) {
return [];
}

return self.events[event].map(callback => callback(data));
}

Store对象(store.js)

该对象主要用于存储共享数据,当数据被更新时触发 stageChange 事件。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import PubSub from '../lib/pubsub.js';
export default class Store {
constructor(params) {
let self = this;
self.actions = {}; // 存储异步方法
self.mutations = {}; // 存储同步方法
self.state = {}; // 共享数据
self.status = 'resting'; // 防止手动更新
self.events = new PubSub();

// 参数可以传入初始的actions和mutations
if(params.hasOwnProperty('actions')) {
self.actions = params.actions;
}

if(params.hasOwnProperty('mutations')) {
self.mutations = params.mutations;
}

// Proxy:es6的方法,起到拦截的作用
self.state = new Proxy((params.state || {}), {
set: function(state, key, value) {

state[key] = value;

console.log(`stateChange: ${key}: ${value}`);

self.events.publish('stateChange', self.state);

// 防止手动更新
if(self.status !== 'mutation') {
console.warn(`You should use a mutation to set ${key}`);
}

self.status = 'resting';

return true;
}
});
}

dispatch(actionKey, payload) { ... }

commit(mutaionKey, payload) { ... }
}

dispatch:调用 actions,可以执行一些异步的操作,然后调用commit

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
dispatch(actionKey, payload) {

let self = this;

if(typeof self.actions[actionKey] !== 'function') {
console.error(`Action "${actionKey} doesn't exist.`);
return false;
}

console.groupCollapsed(`ACTION: ${actionKey}`);

self.status = 'action';

self.actions[actionKey](self, payload);

console.groupEnd();

return true;
}

commit:调用mutations

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
commit(mutationKey, payload) {
let self = this;

if(typeof self.mutations[mutationKey] !== 'function') {
console.log(`Mutation "${mutationKey}" doesn't exist`);
return false;
}

self.status = 'mutation';

let newState = self.mutations[mutationKey](self.state, payload);

self.state = Object.assign(self.state, newState);

return true;
}

案例(状态管理的应用)

需求说明:在首页将一本书加入书架,书架列表自动更新。

store/state.js

1
2
3
export default {
bookList: [],
};

store/mutation.js

1
2
3
4
5
6
export default {
addBook(state, payload) {
state.bookList.push(payload);
return state;
}
};

store/action.js

1
2
3
4
5
export default {
addBook(context, payload) {
context.commit('addBook', payload);
},
};

store/index.js

1
2
3
4
5
6
7
8
9
10
import actions from './actions.js';
import mutations from './mutations.js';
import state from './state.js';
import Store from './store.js';

export default new Store({
actions,
mutations,
state
});

订阅(书架页)

1
2
3
4
5
6
7
import store from '../store/index.js';

store.events.subscribe('stateChange', (params) => {
this.setData({
bookList: params.bookList
});
});

发布(首页)

1
2
import store from '../store/index.js';
store.dispatch('addBook',{bookid: 203});