charto / classy-mst

ES6-like syntax for mobx-state-tree
MIT License
91 stars 5 forks source link

Volatile state definition: how? #2

Closed Codeluck closed 6 years ago

Codeluck commented 6 years ago

Hi there! I would like to define a volatile state object. Here is a piece of my code:

class ElementCode extends ElementData {
    private sign = 1;
    @action
    testAction() {
        this.x += this.sign*20;
        this.sign = -this.sign;
    }
}

Sign variable should make my state volatile. But it's 'undefined' when debugging. It's pretty obvious but my question is what is the best way to define a volatile state in classy-mst? Do I need to define variables in my ElementData class? Wouldn't it be overkill?

jjrv commented 6 years ago

Easiest way might be to use the new model.volatile feature:

import { types } from 'mobx-state-tree';
import { mst, shim, action } from 'classy-mst';

const ElementData = shim(types.model({

    x: 0

}).volatile((self) => ({

    sign: 1

})));

class ElementCode extends ElementData {

    @action
    testAction() {
        this.x += this.sign*20;
        this.sign = -this.sign;
    }

}

const Element = mst(ElementCode, ElementData);

const element = Element.create();

element.testAction();

console.log(element.x);
console.log(element.sign);

It prints:

20
-1
Codeluck commented 6 years ago

Great, thank you! It works like a charm!

jjrv commented 6 years ago

In the latest version 0.2.0 your initial syntax now works as well. However, to support that shim() now only goes in the extendsclause, like this:

const ElementData = types.model({
    x: 0
});

class ElementCode extends shim(ElementData) {
    private sign = 1;
    @action
    testAction() {
        this.x += this.sign*20;
        this.sign = -this.sign;
    }
}