- 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.
- 物聯(lián)網(wǎng)標(biāo)準(zhǔn)化指南
- Web安全防護(hù)指南:基礎(chǔ)篇
- HCNA網(wǎng)絡(luò)技術(shù)
- SD-WAN架構(gòu)與技術(shù)(第2版)
- 企業(yè)私有云建設(shè)指南
- PLC、現(xiàn)場(chǎng)總線及工業(yè)網(wǎng)絡(luò)實(shí)用技術(shù)速成
- 電力物聯(lián)網(wǎng)工程技術(shù)原理與應(yīng)用
- 區(qū)塊鏈輕松上手:原理、源碼、搭建與應(yīng)用
- 物聯(lián)網(wǎng)通信技術(shù)
- 物聯(lián)網(wǎng)長(zhǎng)距離無(wú)線通信技術(shù)應(yīng)用與開發(fā)
- WordPress Web Application Development
- Bonita Open Solution 5.x Essentials
- 夢(mèng)工廠之材質(zhì)N次方:Maya材質(zhì)手冊(cè)
- 一本書讀懂移動(dòng)物聯(lián)網(wǎng)
- 通信系統(tǒng)實(shí)戰(zhàn)筆記:無(wú)處不在的信號(hào)處理