Backbonejs - use nested object as id attribute

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

For example, something like

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

By the way, the above does not work as an identifier, I added it here to give an idea of ​​what I was trying to achieve.

TIA

+4
source share
2 answers

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

But you can directly set the identifier in the model when the response will be served by the server in the parse method

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

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

But usually using nested objects in Backbone Models is unsafe and not the best way to do this. When you change your response.info.name property and bind events to response.info , you will not receive notifications.

After several years of working with Backbone, I would like to tell you that analyzing your received models from the server to primitive objects is the best you can do.

If you want your models to return to the server just like them, you could override the toJSON function, which could convert it. Of course you need to implement these two ...: /

0
source

Source: https://habr.com/ru/post/1486759/


All Articles