- MobX Quick Start Guide
- Pavan Podila Michel Weststrate
- 266字
- 2021-08-05 10:34:21
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.
- 6G潛在關(guān)鍵技術(shù)(下冊)
- 物聯(lián)網(wǎng)之魂:物聯(lián)網(wǎng)協(xié)議與物聯(lián)網(wǎng)操作系統(tǒng)
- Hands-On Chatbot Development with Alexa Skills and Amazon Lex
- Building RESTful Web Services with Spring 5(Second Edition)
- 面向云平臺的物聯(lián)網(wǎng)多源異構(gòu)信息融合方法
- Android UI Design
- React Cookbook
- AIoT應(yīng)用開發(fā)與實(shí)踐
- 局域網(wǎng)組成實(shí)踐
- 計算機(jī)通信網(wǎng)絡(luò)安全
- NB-IoT原理和優(yōu)化
- 人際網(wǎng)絡(luò)
- 黑客心理學(xué):社會工程學(xué)原理
- 路由與交換技術(shù)
- CDN技術(shù)詳解