3

我的模型结构如下:

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

如何将模型的 idAttribute 设置为小部件属性上的 id?有没有语法可以做到这一点?

4

1 回答 1

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.

于 2013-03-10T00:56:39.890 回答