Search code examples
javascriptjquerybackbone.jsunderscore.jshandlebars.js

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

Solution

  • 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.