-
Just wondering if there's a best practice for dealing with multiple nested ES6 classes that should all be observable? Assuming I have a situation where I have a lot of small classes, which will all eventually be rendered/updated through my UI, what's the simplest way to make them all observable? For example, given this: class Foo {
public propA: string;
constructor() {
this.propA = 'some value';
}
} import Foo from './Foo.ts';
class Bar {
public propB: number;
public propFoo: Foo;
constructor() {
this.propB = 10;
this.propFoo = new Foo();
}
} import Bar from './Bar.ts';
class Container {
public propBar: Bar;
constructor() {
this.propBar = new Bar();
}
} What would be the proper way to make all of these observable? I tried doing the following: import { makeAutoObservable, observable } from 'mobx';
import Bar from './Bar.ts';
class Container {
public propC: number;
public propBar: Bar;
constructor() {
this.propC = 0;
this.propBar = new Bar();
makeAutoObservable(this, {propBar: observable});
}
} Since the docs say that should make That's when I noticed this:
I'm not sure if "a plain object" includes ES6 classes or not (or if this might be an issue with TypeScript). It works fine if I explicitly call |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
Yes, each class is responsible for annotating itself. Notice you're not only making the instance observable, but also modifying the prototype (functions become actions etc), so it's good idea to keep it colocated. Btw you're not nesting classes, but composing class instances. Nested or inner class usually refers to ability to define class as part of another class - usually accessible only to the outer class. |
Beta Was this translation helpful? Give feedback.
-
I have a related question. Does class ChildClass {
someProperty: boolean = false;
constructor() {
makeAutoObservable(this);
}
}
class ParentClass {
childStore: ChildClass;
anotherProperty: number = 0;
constructor() {
this.childStore = new ChildClass();
makeAutoObservable(this);
}
} Or do you always have to ignore the field like: |
Beta Was this translation helpful? Give feedback.
Yes, each class is responsible for annotating itself. Notice you're not only making the instance observable, but also modifying the prototype (functions become actions etc), so it's good idea to keep it colocated.
Also note that this recursion process uses
observable(object)
, which creates an observable copy of theobject
, whilemakeAutoObservable(object)
modifies theobject
directly.Btw you're not nesting classes, but composing class instances. Nested or inner class usually refers to ability to define class as part of another class - usually accessible only to the outer class.