官术网_书友最值得收藏!

Observing the state changes

Observables alone cannot make an interesting system. We also need their counterparts, the observers. MobX gives you three different kinds of observers, each tailor-made for the use cases you will encounter in your application. The core observers are autorun, reaction, and when. We will look at each of them in more detail in the next chapter, but let's introduce autorun for now.

The autorun API takes a function as its input and executes it immediately. It also keeps track of the observables that are used inside the passed-in function. When these tracked observables change, the function is re-executed. What is really beautiful and elegant about this simple setup is that there is no extra work required to track observables and subscribe to any changes. It all just happens automatically. It's not magic, per se, but definitely an intelligent system at work, which we will cover in a later section:

import {observable, autorun} from 'mobx';

let cart = observable({
itemCount: 0,
modified: new Date()
});

autorun(() => {
console.log(`The Cart contains ${cart.itemCount} item(s).`);
});

cart.itemCount++;

// Console output:
The Cart contains 0 item(s).
The Cart contains 1 item(s).

In the preceding example, the arrow-function that was passed into autorun is executed for the first time and also when itemCount is incremented. This results in two console logs being printed. autorun makes the passed-in function (the tracking-function) an observer of the observables it references. In our case, cart.itemCount was being observed and when it was incremented, the tracking function was automatically notified, resulting in the console logs getting printed.

主站蜘蛛池模板: 松滋市| 内黄县| 孝昌县| 平顺县| 牡丹江市| 三台县| 逊克县| 临海市| 晋江市| 安远县| 建平县| 专栏| 久治县| 洱源县| 安仁县| 台北县| 左贡县| 尚义县| 韶山市| 潞西市| 景德镇市| 黄浦区| 萍乡市| 南涧| 乐至县| 长治县| 双鸭山市| 金阳县| 阿拉善右旗| 平遥县| 寿宁县| 岐山县| 祁门县| 蒙阴县| 汉源县| 怀化市| 略阳县| 嘉定区| 台安县| 本溪市| 黔东|