Ashwin Hegde
Ashwin Hegde

Reputation: 867

Fetch issues in backbone collection with id

Following is my JSON:

[ 
{  
    "id" : "1",
    "type" : "report"
},
{  
    "id" : "2",
    "type" : "report"
},
{  
    "id" : "1",
    "type" : "email"
},
]

Consider, json is returned from backbone collection -> service call. Now, when I'm using the json response to render my html table using backbone view and handlebars template system. 2 rows gets displayed, instead there should be 3 rows.

Note: collection Parse response is returning correct json (i.e. 3 rows). When I overwrite the id using collection parse with unique random generated number all 3 rows get displayed. This is not ok, because I don't want to change the id.

I want the row to be displayed as following:

1 reports
2 reports
1 email

Upvotes: 0

Views: 311

Answers (2)

MGG
MGG

Reputation: 461

If you want to solve this, you have to set new unique id for each model you add to collection. Try this method:

initialize: function() {
      this.set("id", this.generateID());
},
generateID = function () {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
        return v.toString(16);
    });
}

If you need the original id, you need to save it before, and after create the new one, you set the original in another model attribute. Backbone ignore me when I did @amith-george solution setting idAttribute to another dummyId

Upvotes: 1

Amith George
Amith George

Reputation: 5916

From the documentation for Collection add,

Note that adding the same model (a model with the same id) to a collection more than once is a no-op.

While I cannot see a reason for why two different objects should have the same id, you may have a valid reason. One suggestion would be to add another property to each object in the json response, _dummyId and set that to an autoincrementing value from the server side. On the client side, in your model definition code, you then set the idAttribute to _dummyId.

JSON response,

[ 
{  
    "id" : "1",
    "_dummyId": "1",
    "type" : "report"
},
{  
    "id" : "2",
    "_dummyId": "2",
    "type" : "report"
},
{  
    "id" : "1",
    "_dummyId": "3",
    "type" : "email"
},
]

Your model definition, from http://backbonejs.org/#Model-idAttribute,

var Meal = Backbone.Model.extend({
  idAttribute: "_dummyId"
});

That said, I do hope there is an elegant setting in backbone, something that makes a backbone collection acts a list instead of a set.

Upvotes: 2

Related Questions