2

I'm using backbone relational for my collection handling.

I have a complex object which may have duplicated ids inside. e.g.

{
    id: "things/1",
    children: [
    {
        id: "things/2",
        children: [
        {
            id: "things/3",
            children: null
        }
        ]
    },
    {
        id: "things/4",
        children: [
        {
            id: "things/3",
            children: null
        }
        ]
    },
    ]
}

I then try and use this as a relational collection, like so. (written in TypeScript).

constructor(options?) {
    // ...
    this.idAttribute = 'Id';
    this.relations = [{
        type: Backbone.HasMany,
        key: 'Children',
        relatedModel: 'Application.Models.MyModel',
        collectionType: 'Backbone.Collection'
    }
    ];
    super(options);
}

As soon as I get duplicate ids from the server, however, BBR angrily throws an exception and things just don't happen. "Duplicate id!"

Should I be perhaps generating some sort of fake id based on a guid for these models? Or is there a way to tell the Backbone Relational store to stop enforcing this rule? Maybe I can just turn off the store altogether.

I'm not using this to do any collection fetches, fetch relateds, or anything like that. I'm really using it as a nice way of parsing a recursive data structure.

I've ran into this problem often when writing Jasmine tests as well, but managed to get around it by adding a random *10 multiplyer for each test to make sure the ids are different. But it's a pain in the neck to have to do this. So hopefully any fixes here will help me in unit testing as well.

I'm not averse to trying a different framework, but some models in my project use BBR, so it'd need to play nice. If there's something else out there that'd be more appropriate, feel free to suggest it, too.

Craig Brett
  • 2,295
  • 1
  • 22
  • 27

2 Answers2

0

Your data structure implies a strict tree-like relationship, while the data clearly isn't organized like that. Either make your data an actual tree, where each node is unique, or represent it with a structure that can handle more complex relationships.

I would suggest you just send the objects as a flat array, where each node has a childrenIds array. Then you can easily restore the children arrays after receiving the objects.

geon
  • 8,128
  • 3
  • 34
  • 41
0

My eventual answer to this was to move to Backbone Associations. After writing a d.ts file (available on the DefinitelyTyped repository) and some initial refactoring to change the relations blocks, things pretty much work off the bat! The only thing you need to remember is to set any collections by default to an empty array in the defaults function of your model. Hope this helps someone!

Craig Brett
  • 2,295
  • 1
  • 22
  • 27