mobx-state-tree icon indicating copy to clipboard operation
mobx-state-tree copied to clipboard

Convert Class to Tree Node

Open doc987 opened this issue 5 years ago • 1 comments

Suppose that there is a large existing code base. Is there a way to convert classes (or equivalent functions) to MobX State Tree nodes without rewriting the code in terms of MobX State Tree? For example, given the class (C) shown below, how can the node (MSTNode) shown below be automatically generated (e.g. MSTNode = makeNodeFromClass(C))?

import * as mst from "./mobx-state-tree.module.js";

class C {
	prop1 = 0;
	prop2 = "";
	prop3 = false;
	get get1(){ /* ... */ }
	get get2(){ /* ... */ }
	action1(){ /* ... */ }
	action2(){ /* ... */ }
}

const MSTNode = mst.types
	.model({
		prop1: 0,
		prop2: "",
		prop3: false,
	})
	.views( self => ({
		get get1(){ /* ... */ },
		get get2(){ /* ... */ },
	}))
	.actions( self => ({
		action1(){ /* ... */ },
		action2(){ /* ... */ },
	}))
;

doc987 avatar Sep 06 '20 01:09 doc987

I have a project where we do something similar.

https://github.com/terrysahaidak/mst-collection

the only different from regular classes is that you need to specify the model props - which properties of your class should be serialized and how. All the other class properties are volatile.

const MSTModel = types.model("MyModel", {
  prop1: types.string,
})
.volatile(() => ({
  prop2: 1
}))
.views(() => ((
  get thisIsView () {}
}))
.actions(() => ((
  action () {}
}))

class _MSTModel extends Model({
  prop1: types.string,
}) {
  prop2 = 1;

  get thisIsView () {}

  action() {}
}
const MSTModel = model(_MSTModel)

It might be not perfect from the typings perspective, I'm still migrating my current project from regular models to this. But should work for like 99% cases I guess.

terrysahaidak avatar Sep 06 '20 06:09 terrysahaidak

Hey @doc987, I'm going to label this issue for closing since it looks like @terrysahaidak had a pretty good option for ya here and there hasn't been much movement.

I'll come back in a week or two and close it out if no one objects. Thanks!

coolsoftwaretyler avatar Jun 28 '23 21:06 coolsoftwaretyler

No response for about two weeks or so - gonna close this one out!

coolsoftwaretyler avatar Jul 13 '23 22:07 coolsoftwaretyler