Observable vs @observable

Mobx supports declaring an observable either as myObservableVariable = observable({......}) or by using a decorator, i.e.:

myObservableClassProperty = {......};

There is a very important difference between these two. Using a decorator not only makes the properties of the object in myObservableClassPropertyobservable, it also makes the myObservableClassPropertyproperty of your class instances observable so that placing a new object in it will cause observers to react, at which point they'll reference properties of this new object and so will subsequently react to changes in the new object.

On the other hand, placing a new object in myObservableVariablewill have no effect on observers as they will continue to observe the old object.

Because MobX cannot react to newly added properties in an observable object, the ability to replace the whole object with one that has new properties provides for an effective workaround in many situations.

Although the decorators approach works well for class properties, it is not yet supported for plain object properties. Sometimes in singleton classes it is convenient to have 'private' observables. To enable replacement of the entire object in such an observable, use the following pattern:

import { extendObservable } from 'mobx';

const obs = {};

extendObservable(obs, { myObservable: {......} });

// now you can observe obs.myObservable and obs.myObservable = {......} will cause its observers
// to react and observe changes to the new object thereafter

results matching ""

    No results matching ""