AmpersandJS / ampersand-state

Core state management object.
MIT License
141 stars 75 forks source link

state.collections referecing itself #220

Open vwasteels opened 8 years ago

vwasteels commented 8 years ago

Hello

I am dealing with hierchical data, and trying to implement it this way :

var State = require('ampersand-state');
var Collection = require('ampersand-collection');

var Instance = State.extend({
    modelType: 'Instance',

    props: {
        id: 'number',
        slug: 'string',
        name: 'string'
    },

    collections: {
        children: Collection.extend({ type: 'instances', model: Instance })
    }
});

this is working almost right, the problem is that parent and children doesn't have the same format :

// to fetch direct children I can do :
rootInstance.children.models;

// but for deeper children, I only have to do :
childInstance.children

It looks like children item are not completely build... Am I right ?

vwasteels commented 8 years ago

more precisely : it seems that collections in subitems are not instanciated as ampersand-collection, they remains arrays

wraithgar commented 8 years ago

At a glance it appears this may be true. If you pass a bare object to children it is not converted to a model. Working example here: http://requirebin.com/?gist=a4da9d25b8c2188a5397

latentflip commented 8 years ago

Possibly related to: https://github.com/AmpersandJS/ampersand-state/issues/146 and or https://github.com/AmpersandJS/ampersand-state/issues/106 ?

vwasteels commented 8 years ago

@wraithgar thanks for the requirebin ! please look at this one which better explains the situation with the subchild children collection : http://requirebin.com/?gist=7cf86f5461c825405ade

@latentflip :

146 refers to the children props which is not instanciated with State.initialize

106 also refer to the children props

But my example is ambigous since the key of my collection item is called "children" ;)

vwasteels commented 8 years ago

Hello,

Is there any update regarding this issue ?

I found a workaround last time by testing if the collection had been initialized before using it, like this : `var models = collection.models ? collection.models : collection.children;``

but I'm now stuck because since sub collections are not initialized, I don't have access to custom methods I wrote for them. It's really a mess to work with hierarchical data in this situation, I'm curious to know how people handle it ... any idea ?

thanks :)

vwasteels commented 8 years ago

I guess one solution would be to override the set method to recursively instanciate sub collections , I'll try something and keep this thread updated