Dan
Dan

Reputation: 991

Backbone custom collections from JSON data

This is a bit confusing, and I have no code to paste in here but would appreciate any help. I ran into an issue when I have this hypothetical setup using Backbone. These are preset:

now if I do the following

postoffice.add([
{
    "id": "mailbox1",
    "messages": [
        {
            "id": "message1"
        },
        {
            "id": "message2"
        }
    ]
},
{
    "id": "mailbox2",
    "messages": [
        {
            "id": "message1"
        },
        {
            "id": "message2"
        }
    ]
},
{
    "id": "mailbox2",
    "messages": [
        {
            "id": "message1"
        },
        {
            "id": "message2"
        }
    ]
}
])

I would expect each blank Mailbox.messages collection to be populated with Message models created from the JSON data. What actually happens is that each Mailbox gets a new "collection" attribute that gets the message data. This however won't work for me since the models inside that default collection dont get the Message model structure.

Is there anyway or workaround that lets me map arrays in the JSON object to the correct type of preset collections?

Upvotes: 0

Views: 735

Answers (1)

timDunham
timDunham

Reputation: 3318

I think what might help you is something like Backbone Relational. It will allow you to define relationships between you different models.

If you're looking to roll something on your own, you could do something like the following in your initialize for your Mailbox model:

initialize: function(attr, options) {
    this.Messages= new MessagesCollection(attr.messages);
    delete this.attributes.messages
}

By doing that you would have a Messages backbone collection for each Mailbox in your PostOffice. The delete statement would remove it from being an attribute... so Mailbox.get('messages') would no longer work.

Hope that helpes

Upvotes: 1

Related Questions