source.rar
source.rar

Reputation: 8090

Backbonejs - use nested object as id attribute

Is it possible to use a nested object as the id attribute in Backbone?

For e.g. something like,

var MyModel = Backbone.Model.extend({
        defaults : {
            'info': {
                'name': ""
            },
        },
        idAttribute: "info.name"
}

BTW, the above doesn't work as an ID, I added it here just to give an idea of what I was trying to achieve.

TIA

Upvotes: 4

Views: 1113

Answers (2)

Luke
Luke

Reputation: 8407

as @Sushanth says, parse is for sure a good way to do this.

But generally using nested objects within Backbone Models is unsafe and not the best way to do it. When you change your response.info.name property, and you bind events to response.info, you will not get notified.

After a few years with Backbone, I would like to tell you, that parsing your received models from server into primitive objects is the best you can do.

If you want your models to go back to server exactly the same way they came in, you could override the toJSON function, which could transform it back. Of course, you need to implement those two... :/

Upvotes: 0

Sushanth --
Sushanth --

Reputation: 55750

I don't think you can directly assign a nested object as an idAttribute .

But you can directly set the id on the model when the response is served by the server in the parse method

parse: function(response) {
   response.id = response.info.name;
   return response;
}

Upvotes: 4

Related Questions