3

My model is structured like this:

model = {
    distance: 12.05,
    widget: {
        id: 1,
        creationDate: '12/01/2012'
    }
}

How do I set the idAttribute of the model to be the id on the widget property? Is there a syntax to do this?

1 Answers1

2

How about rearranging/flattening your model to make id a top-level property? Override parse and you won't need to set the idAttribute:

var YourModel = Backbone.Model.extend({
    parse: function (response) {
        var distance = response.distance;
        response = response.widget;
        response.distance = distance;
        return response;
    }
});

Now id will be automatically picked up by Backbone as the id. If you need to persist your data back to your datastore, you'll need to overwrite methods necessary to transform the data back. If possible, it would be a better solution if your model came structured with id already at a top level.

kinakuta
  • 9,029
  • 1
  • 39
  • 48
  • I don't have any say in how I receive the data, so while I'd like to get the data with the id as a top level attribute, it's simply not a possibility. What kind of performance hit would rearranging data in this fashion be? –  Mar 10 '13 at 01:00
  • 1
    It depends. Are you transforming very large quantities of these models, and how frequently? – kinakuta Mar 10 '13 at 01:03