- 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.
- 網管員典藏書架:網絡管理與運維實戰寶典
- 網絡故障現場處理實踐(第4版)
- 新一代物聯網架構技術:分層算力網絡
- HCNA網絡技術
- 計算機網絡安全實訓教程(第二版)
- Web Application Development with R Using Shiny
- 局域網組建、管理與維護項目教程(Windows Server 2003)
- 網絡的琴弦:玩轉IP看監控
- 計算機網絡與通信(第2版)
- 區塊鏈輕松上手:原理、源碼、搭建與應用
- 數字調制解調技術的MATLAB與FPGA實現:Altera/Verilog版(第2版)
- TD-LTE無線網絡規劃與設計
- 紅藍攻防:構建實戰化網絡安全防御體系
- 現代通信系統(第5版)
- Laravel Application Development Cookbook