Backbone.js:无法将相同的模型添加到集合中两次

vik*_*tra 3 javascript backbone.js

我刚开始使用backbone.js.我在从服务器获取数据时遇到问题.这是我从服务器获得的响应.

[{
  "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"
}]
Run Code Online (Sandbox Code Playgroud)

这是我的javascript代码......

// 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();
    }
};
Run Code Online (Sandbox Code Playgroud)

我在Backbone.js中的这一行上收到错误"无法将相同的模型添加到两次"

if (already) throw new Error(["Can't add the same model to a set twice", already.id]); 
Run Code Online (Sandbox Code Playgroud)

我检查了Backbone.js注释,发现第一个模型被添加到集合中,但第二个模型给出了这个错误.为什么会这样?我应该更改服务器端响应中的内容吗?

Pet*_*ons 8

List拥有id它的defaults属性,默认情况下每个实例都有相同的ID,Backbone正在使用它来检测欺骗.如果您的数据使用list_id的ID,你需要通过将告诉科博idAttribute: 'list_id'你的内部List类的定义.

另外,我更喜欢不在对象属性中复制类型信息(Backbone.js同意这一点).具有一致的属性名称是骨干所期望的并且更易于使用.因此,而不是有list_idlist_name,只使用id,并name在所有类.