Writing in the front
State management is the core of modern front-end development. In order to solve the complexity of front-end applications, a variety of state management schemes are born in the ecosystem, classified as functional (Redux), responsive (RXJS), transparent functional responsive (MOBX) according to the programming paradigm, and classified as single-store and multi-store according to the state storage. There are those that deal specifically with asynchronous code (RXJS) and those that don’t (Redux)….. , basically can meet the front-end application of various scenarios.
However, due to the closed ecosystem of small programs, the binding libraries of various state schemes cannot be used in small programs. An existing binding library is not available? So let’s write one.
Goals for state management
Before stepping into the main body, let’s talk about some of our demands for a state management solution:
- Based on the existing state management scheme, REdux, MOBx, RXJS, reuse the existing ecology to the maximum extent
- Typescript friendly (TS smells good)
- The API is simple and clear, the performance baseline is high, and good performance can be achieved without manual optimization.
- Less template code, more code on my hands
RXJS learning curve is too steep and does not define how state is stored. Cross it out. Redux is a lot of concepts, template code as much as concepts, don’t. That leaves Mobx.
API
First define the Store and connect to the page.
observer(context, mapState)
import { observable } from 'mobx';
import { observer } from 'mobx-mini';
const rootStore = observable({
title: 'mobx-app'
});
const store = observable({
count: 0,
get isOdd() {
return this.seconds % 2= = =1;
},
tick() {
this.count += 1; }});const mapState = (a)= > ({
count: store.count,
seconds: store.isOdd,
title: rootStore.title,
});
// page
Page({
add() {
store.tick();
},
onLoad() {
observer(this, mapState); }});Copy the code
Use it directly in AXML
<view>count</view>
Copy the code
Realize the principle of
If you are not already familiar with Mobx, it is recommended that you take a look at its Chinese documentation for a primer. The principle is that the Observer APi registers autorun function on the Observable object in parameter mapState. Inside Autorun, after monitoring observable changes, setData is directly applied to the page. The data of the applet will be dynamically updated.
conclusion
As a reminder, only Alipay applets are supported for the time being and have not been used in production environments. The source code is here, less than 100 lines. Github.com/luv-sic/mob…
reference
Cn.mobx.js.org/ github.com/b5156/mobx-…