How to use the makeAutoObservable function from mobx
Find comprehensive JavaScript mobx.makeAutoObservable code examples handpicked from public code repositorys.
MobX.makeAutoObservable is a utility function that automatically makes class properties observable and creates corresponding actions for modifying them.
124 125 126 127 128 129 130 131 132 133
eventSequenceDictName = "midiEventSequence"; eventSequence; constructor(rootStore) { // i.e. quantizedEventSequence = [{"36": [2, 100], "42": [0, 127]}, ...] makeAutoObservable(this); this.root = rootStore; this.eventSequence = new EventSequence(); this.reactToParamsChange = reaction(
How does mobx.makeAutoObservable work?
MobX.makeAutoObservable works by leveraging the ECMAScript decorators syntax or Object.defineProperty to automatically instrument the class's properties with MobX's observable capabilities. This includes defining a setter for each property that triggers MobX's observer mechanism and also adding an action method for each property to modify its value, with automatic tracking of dependencies for computations. When a class property is updated, any observers that depend on it will be automatically notified, and any computed values that depend on it will be recomputed. This simplifies the process of creating observable state in a MobX application, as it removes the need to manually annotate each class property with MobX's observable capabilities. Instead, developers can simply use makeAutoObservable to automatically instrument the entire class with MobX's observable features.
Ai Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
import { makeAutoObservable } from "mobx"; class CounterStore { count = 0; // Initialize a class property with a default value constructor() { makeAutoObservable(this); // Automatically make all class properties observable } increment() { this.count++; // Automatically create an action method to modify the 'count' property } decrement() { this.count--; // Automatically create an action method to modify the 'count' property } } export default new CounterStore(); // Export a singleton instance of the CounterStore class
In this example, we define a simple CounterStore class with a single observable property (count) initialized to a default value of 0. We then use makeAutoObservable(this) in the constructor to automatically make all of the class's properties observable and create corresponding action methods for modifying them. This allows us to increment or decrement the count property using the increment() and decrement() methods, respectively. Because the count property is observable, any React components that depend on it will automatically re-render whenever it is updated.
mobx.runInAction is the most popular function in mobx (1598 examples)