4

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

2
  • you cannot use a nested object as an idattribute Commented Jun 18, 2013 at 8:58
  • If you have something mutable (such as an {info: { ... } } object) in your defaults, use a defaults function instead of an object literal. The defaults are shallow copied so you're going to end up changing the prototype's defaults and wonder why all your models have changed. Commented Jun 18, 2013 at 16:17

2 Answers 2

4

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;
}
Sign up to request clarification or add additional context in comments.

2 Comments

Just a note that not supporting nested idAttributes is by design and will not change: github.com/jashkenas/backbone/pull/598
This won't always work as you expect, because models are not parsed before they are set on the collection. Calling collection.fetch({ remove: false }) will therefore result in duplicate models. See this jsfiddle.
0

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... :/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.