Skip to content

Instantly share code, notes, and snippets.

@gaperton
Last active March 8, 2018 23:19
Show Gist options
  • Save gaperton/5dcf3719af89648cf52e9160b8708799 to your computer and use it in GitHub Desktop.
Save gaperton/5dcf3719af89648cf52e9160b8708799 to your computer and use it in GitHub Desktop.
mobx serializer example with Type-R
import { define, Record } from 'type-r';
@define
export class Box extends Record {
static attributes = {
x : Number,
y : Number,
location : String
}
get area() {
return this.x * this.y;
}
}
@define
export class Arrow extends Record {
static attributes = {
from : Box.from( '~boxes' ),
to : Box.from( '~boxes' )
}
}
import { define, Store } from 'type-r'
// The store that holds our domain: boxes and arrows
@define class MyStore extends Store {
static attributes = {
boxes : Box.Collection,
arrows : Arrow.Collection,
selection : Box.from( 'boxes' )
}
}
function randomId() {
return Math.floor(Math.random() * 100000);
}
// Example Data
// You can push data in as a class
const store = new MyStore();
store.boxes.add([
new Box({ id: randomId(), location : 'Rotterdam', x : 100, y : 100 }),
new Box({ id: randomId(), location : 'Vienna', x : 650, y : 300 })
]);
// Or it can be an raw javascript object with the right properties
store.arrows.add({
id: randomId(),
from: store.boxes.at(0),
to: store.boxes.at(1),
});
const json = store.toJSON();
// Print ... out for debugging
console.dir( json, { depth: 10, colors: true });
store.set( json, { parse : true } );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment