Creating Observable Properties

Without Decorators

Without decorators extendObservable can be used to introduce observable properties on an object. Typically, this is done inside a constructor function. The following example introduces observable properties, a computed property, and an action in a constructor function / class:

function Timer() {
    extendObservable(this, {
        start: Date.now(),
        current: Date.now(),
        get elapsedTime() {
            return (this.current - this.start) + "milliseconds"
        },
        tick: action(function() {
              this.current = Date.now()
        })
    })
}

Or, when using classes:

class Timer {
    constructor() {
        extendObservable(this, {
            /* See previous listing */
        })
    }
}

With Decorators

Decorators combine very nicely with classes. When using decorators, observables, computed values and actions can be simply introduced by using the decorators:

class Timer {
    @observable start = Date.now();
    @observable current = Date.now();

    @computed get elapsedTime() {
        return (this.current - this.start) + "milliseconds"
    }

    @action tick() {
        this.current = Date.now()
    }
}

results matching ""

    No results matching ""