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

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.

主站蜘蛛池模板: 阜康市| 呼图壁县| 姚安县| 贵德县| 喀什市| 建水县| 泸州市| 桦川县| 阿拉善右旗| 四会市| 长海县| 惠安县| 阿克陶县| 峨眉山市| 阿巴嘎旗| 永城市| 精河县| 滦南县| 宁阳县| 上林县| 中卫市| 长兴县| 通许县| 天峨县| 久治县| 台湾省| 武陟县| 临沂市| 青州市| 天门市| 麻江县| 克拉玛依市| 大兴区| 九寨沟县| 临洮县| 海原县| 加查县| 若尔盖县| 神农架林区| 庄河市| 天水市|