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

  • 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 still a pending proposal  (as of this writing) for inclusion in the JavaScript language standard. But that doesn't stop us from using it, as we have Babel to help us out. By using the Babel plugin, transform-decorators-legacy, we can transpile the decorator syntax into regular ES5 code. If you are using TypeScript, you can also enable decorator support by setting your  { experimentalDecorators: true} compiler option in your tsconfig.json

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.

主站蜘蛛池模板: 水富县| 辰溪县| 中西区| 永嘉县| 神木县| 东平县| 渭南市| 彭泽县| 葵青区| 大兴区| 仙桃市| 洛浦县| 青龙| 黄梅县| 武胜县| 平谷区| 锡林郭勒盟| 观塘区| 泾川县| 清徐县| 安吉县| 昌乐县| 孟州市| 会同县| 临武县| 江孜县| 新龙县| 磴口县| 深水埗区| 青海省| 东山县| 榆社县| 轮台县| 子洲县| 长泰县| 叶城县| 三台县| 原阳县| 杭锦旗| 武威市| 铁力市|