Backbone.js的:同型号无法添加到一组的两倍 [英] Backbone.js: Can't add the same model to a set twice

查看:69
本文介绍了Backbone.js的:同型号无法添加到一组的两倍的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚开始用Backbone.js的。而我在从服务器获取数据有问题。下面是我从服务器获取响应。

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"
}]

下面是我的javascript code ...

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();
    }
};

我得到的错误在Backbone.js的这一行

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]); 

我检查了Backbone.js的注释,并发现了第一种模式被添加到集合,但第二个给出了这样的错误。这究竟是为什么?我应在服务器端的响应改变些什么?

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?

推荐答案

列表 ID 默认属性,它是使每个实例都默认的相同的ID和骨干被使用来检测愚弄。如果您的数据使用 LIST_ID 作为ID,你需要告诉到骨干通过把 idAttribute:LIST_ID内你的列表类的定义。

Your List has id in its defaults property, which is making each instance have the same ID by default, and Backbone is using that to detect dupes. If your data uses list_id as the ID, you need to tell that to Backbone by putting idAttribute: 'list_id' inside your List class definition.

顺便说一句,我preFER对象的属性(和Backbone.js的同意这一点),以不重复的类型信息。拥有一致的属性名是骨干期待并为更容易使用。因此,而不是有 LIST_ID LIST_NAME ,只需要使用 ID 名称上的所有课程。

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_id and list_name, just use id, and name on all classes.

这篇关于Backbone.js的:同型号无法添加到一组的两倍的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆