Search code examples
backbone.jsbackbone-relational

Backbone Relational collection with duplicate ids


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.


Solution

  • 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!