I have just started with backbone.js. And I’m having a problem in fetching the data from the server. Here’s the response I’m getting from server.
[{
"list_name":"list1",
"list_id":"4",
"created":"2011-07-07 21:21:16",
"user_id":"123456"
},
{
"list_name":"list2",
"list_id":"3",
"created":"2011-07-07 21:19:51",
"user_key":"678901"
}]
Here’s my javascript code…
// Router
App.Routers.AppRouter = Backbone.Router.extend({
routes: {
'': 'index'
},
initialize: function() {
},
index: function() {
var listCollection = new App.Collections.ListCollection();
listCollection.fetch({
success: function() {
new App.Views.ListItemView({collection: listCollection});
},
error: function() {
alert("controller: error loading lists");
}
});
}
});
// Models
var List = Backbone.Model.extend({
defaults: {
name: '',
id: ''
}
});
App.Collections.ListStore = Backbone.Collection.extend({
model: List,
url: '/lists'
});
// Initiate Application
var App = {
Collections: {},
Routers: {},
Views: {},
init: function() {
var objAppRouter = new App.Routers.AppRouter();
Backbone.history.start();
}
};
I get the error “Can’t add the same model to a set twice” on this line in Backbone.js
if (already) throw new Error(["Can't add the same model to a set twice", already.id]);
I checked out the Backbone.js annotated and found out that the first model gets added to the collection but the second one gives this error. Why is this happening? Should I change something in the server side response?
Your
Listhasidin itsdefaultsproperty, which is making each instance have the same ID by default, and Backbone is using that to detect dupes. If your data useslist_idas the ID, you need to tell that to Backbone by puttingidAttribute: 'list_id'inside yourListclass definition.As an aside, I prefer to NOT duplicate type information in object attributes (and Backbone.js agrees on this point). Having consistent attribute names is what backbone expects and is easier to work with. So instead of having
list_idandlist_name, just useid, andnameon all classes.