MobX is a simple and effective state management library, with the concept of derive as the core, with the observer mode as the means, to achieve the purpose of automatic update interface modification data

  • Because react provides a way to wrap the React component and make it easy to improve, the react and ES7 decorator features are the starting point for the documentation and almost all tutorials

  • However, MobX works well in a traditional ES5 environment. This paper tries to use this as a starting point to discuss how to directly introduce MobX into existing non-React projects and use it to refactor old code

No Babel, Webpack, JSX… So many routines! Go ahead and get started

[I]. Core concepts and basic processes

The name of the role
state The data used to drive the application
The derived Data or actions generated from core data, such as computed and Reaction, mentioned below
observable Core data that can be observed
action Method used to change state, and only here can change state
computed Values derived from changes in core data or other computed data, such as the length of an array
reaction Similar to computed, observer methods, which derive from changes in data and automatically perform “side-effects” tasks such as UI changes or network requests, are either either reactionun or reactionFn

1.1 Example of a counter

<script src="https://unpkg.com/mobx/lib/mobx.umd.js"></script>

<div id="counter">
    <button class="dec">-</button>
    <span></span>
    <button class="inc">+</button>
</div>Copy the code
.nagetive {
    color: red;
}Copy the code
$(document).ready(function(){// Strictly restrict changing data only in action mobx.usestrict (true); / / interface element reference var $ct = $(' # counter), $btn_inc = $ct. The find (' inc '), $btn_dec = $ct. The find (' dec '), $num = $ct. The find (" span "); /** * observable() {/** * observable() {/** * observable() {/** * observable(); Get style() {return this.count>0? '' : 'nagetive'; }, //action increment: mobx.action(function() { this.count++; }), //action decrement: mobx.action(function() { this.count--; })}); // /reaction function render() {$num.html(appstate.count); $num.get(0).className = appState.style; } mobx.autorun(render); $btn_inc. On ('click', function() {appstate.increment (); }); $btn_dec.on('click', function() { appState.decrement(); }); });Copy the code


* Original article reproduced please indicate the source

————————————-

Long press the QR code to follow our official account oh: