- MobX Quick Start Guide
- Pavan Podila Michel Weststrate
- 134字
- 2021-08-05 10:34:25
Decorating actions
The use of decorators is pervasive in MobX. Actions also get special treatment with the @action decorator to mark class methods as actions. With decorators, the Cart class can be written as shown here:
class Cart {
@observable modified = new Date();
@observable.shallow items = [];
@action
addItem(name, quantity) {
this.items.push({ name, quantity });
this.modified = new Date();
}
@action.bound
removeItem(name) {
const item = this.items.find(x => x.name === name);
if (item) {
item.quantity -= 1;
if (item.quantity <= 0) {
this.items.remove(item);
}
}
}
}
In the preceding snippet, we used @action.bound for the removeItem() action. This is a special form that pre-binds the instance of the class to the method. This means you can pass around the reference to removeItem() and be assured that the this value always points to the instance of the Cart.
A different way of declaring the removeItem action with a pre-bound this is with the use of class properties and arrow-functions. This can be seen in the following code:
class Cart {
/* ... */
@action removeItem = (name) => {
const item = this.items.find(x => x.name === name);
if (item) {
item.quantity -= 1;
if (item.quantity <= 0) {
this.items.remove(item);
}
}
}
}
Here, removeItem is a class-property whose value is an arrow-function. Because of the arrow-function, it binds to the lexical this, which is the instance of the Cart.
- 網(wǎng)絡(luò)教育學(xué)習(xí)指導(dǎo)
- 高校網(wǎng)絡(luò)道德教育研究
- 物聯(lián)網(wǎng)識(shí)別技術(shù)
- 物聯(lián)網(wǎng)安全:理論、實(shí)踐與創(chuàng)新
- INSTANT PhpStorm Starter
- 萬(wàn)物互聯(lián):蜂窩物聯(lián)網(wǎng)組網(wǎng)技術(shù)詳解
- HCNA網(wǎng)絡(luò)技術(shù)
- Spring Cloud微服務(wù)架構(gòu)進(jìn)階
- 無(wú)人機(jī)通信
- PLC、現(xiàn)場(chǎng)總線及工業(yè)網(wǎng)絡(luò)實(shí)用技術(shù)速成
- 射頻通信系統(tǒng)
- 物聯(lián)網(wǎng)安全技術(shù)
- Mastering JavaFX 10
- WordPress Web Application Development
- CCNP TSHOOT(642-832)認(rèn)證考試指南