官术网_书友最值得收藏!

  • 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.

主站蜘蛛池模板: 江都市| 壤塘县| 新乡县| 巴彦淖尔市| 彩票| 建平县| 安宁市| 许昌市| 灵璧县| 建水县| 磴口县| 宜都市| 谷城县| 嘉兴市| 加查县| 游戏| 汾阳市| 普兰店市| 逊克县| 梁平县| 巫溪县| 长垣县| 蚌埠市| 莱芜市| 光泽县| 瑞金市| 伊川县| 西乌珠穆沁旗| 贵阳市| 广饶县| 永定县| 广安市| 林口县| 宣恩县| 溆浦县| 长宁区| 醴陵市| 泽州县| 双鸭山市| 开封县| 黄梅县|