- MobX Quick Start Guide
- Pavan Podila Michel Weststrate
- 385字
- 2021-08-05 10:34:24
Better syntax with decorators
All of our examples so far have used the ES5 API of MobX. However, there is a special form of the API, which gives us a very convenient way of expressing the observables. This is made possible with the @decorator syntax.
The decorator syntax is only available for classes and can be used for class declarations, properties and methods. Here is an equivalent Cart observable, expressed with decorators:
class Cart {
@observable.shallow items = [];
@observable modified = new Date();
@computed get description() {
switch (this.items.length) {
case 0:
return 'There are no items in the cart';
case 1:
return 'There is one item in the cart';
default:
return `There are ${this.items.length} items in the
cart`;
}
}
}
Notice the use of decorators to decorate the observable properties. The default @observable decorator does deep observation on all the properties of the value. It is actually a shorthand for using @observable.deep.
Similarly, we have the @observable.shallow decorator, which is a rough equivalent of setting the { deep: false } option on the observable. It works for objects, arrays, and maps. We will cover the more technically correct ES5 equivalent of observable.shallow in Chapter 4 , Crafting the Observable Tree.
The snippet below shows the items and metadata properties, marked as shallow observables:
class Cart {
// Using decorators
@observable.shallow items = [];
@observable.shallow metadata = {};
}
We will be covering a few more decorators in a later chapter, but we did not want to wait until then to discuss the decorator syntax. We definitely think you should pick decorators as your first choice for declaring observables. Note that they are only available inside classes. However, the vast majority of the time, you will be using classes to model your observable tree, so decorators greatly help in making it more readable.
- 自動(dòng)駕駛網(wǎng)絡(luò):自智時(shí)代的網(wǎng)絡(luò)架構(gòu)
- 物聯(lián)網(wǎng)安全(原書(shū)第2版)
- 光網(wǎng)絡(luò)評(píng)估及案例分析
- 電子政務(wù)效益的經(jīng)濟(jì)分析與評(píng)價(jià)
- 重新定義Spring Cloud實(shí)戰(zhàn)
- 計(jì)算機(jī)網(wǎng)絡(luò)與數(shù)據(jù)通信
- Drush User’s Guide
- 物聯(lián)網(wǎng)時(shí)代
- Mastering TypeScript 3
- C/C++串口通信:典型應(yīng)用實(shí)例編程實(shí)踐
- Web用戶查詢(xún)?nèi)罩就诰蚺c應(yīng)用
- 黑客與反黑工具使用詳解
- 國(guó)外物聯(lián)網(wǎng)透視
- 深入理解Kubernetes網(wǎng)絡(luò)系統(tǒng)原理
- 物聯(lián)網(wǎng)工程應(yīng)用技術(shù)