sylvainpolletvillard / ObjectModel

Strong Dynamically Typed Object Modeling for JavaScript
http://objectmodel.js.org
MIT License
467 stars 30 forks source link

self-referenced object #118

Closed thipages closed 4 years ago

thipages commented 4 years ago

Hi, I would like to define the model as a property as well Obviously, the code below is not working.

I can trick it by replacing children by ArrayModel(Number), Number representating an A id Did I miss something? Thank you.

const A=Model(
    {
        id:Number,
        children:ArrayModel(A)
    }
);
sylvainpolletvillard commented 4 years ago

Hello,

This question has been answered in the Common questions section of the website: http://objectmodel.js.org/#common-questions

How should I deal with circular references in my model definitions ?

const A=Model(
    {
        id:Number,
        children:ArrayModel(undefined)
    }
);
A.definition.children.definition = A
thipages commented 4 years ago

Thank you! Here is a corresponding example

const A=Model(
    {
        id:Number,
        children:ArrayModel(undefined)
    }
);
A.definition.children.definition=A;

const qA=(id)=>A({id,children:[]});
const a1=qA(1);
const a2=qA(2);
const a3=qA(3);
a1.children=[a2,a3];
a2.children=[a1];

console.log(a1.children[0].id); // returns 2