我正在尝试从服务器中获取一个集合。
我正在使用版本0.3.3(不是github的高手)
但是我在此异常中运行:

Uncaught TypeError: Cannot use 'in' operator to search for 'id' in {id=MyId, active=true}
    jQuery.jQuery.extend._Deferred.deferred.resolveWith (jquery.js:869)
    done (jquery.js:6591)
    jQuery.ajaxTransport.send.callback

这是我创建错误的方式:
var MyModel = Backbone.Model.extend();
var MyCollection = Backbone.Collection.extend({
    url: '/api/collection',
    model: MyModel
});
var coll = new MyCollection();
coll.fetch();

/ api / collection中的元素以JSON解析。
我试图以各种格式退还它们
["Id1", "Id2", ... ]
[{id: "Id1, somethingElse: "..."}, ...]
{id1: { id1s content}, id2: { ... }, ...}

但是错误始终是相同的。
此代码有什么问题?

[编辑] 通过coll.fetch({error: errorFunc});设置错误无济于事。异常(exception)保持不变。

[Edit2] collection.fetch()用响应对象调用collection.refresh()之前,似乎一切正常。我没有覆盖任何这些功能。

[Edit3] 错误在于collection.add()方法中,原因是我的元素是字符串列表。我的服务器向他们发送了错误消息。

最佳答案

由于您已经确定响应格式不是Backbone期望的格式,因此您应该覆盖 YourModel.parse 函数,该函数应从服务器获取响应并返回集合可以接受的模型数组。这是Backbone.js的片段

// **parse** converts a response into a list of models to be added to the
// collection. The default implementation is just to pass it through.
parse : function(resp) {
  return resp;
},

如您所见,默认功能只是传递数据。您必须使它适用于您的响应格式。

附言id建议在Backbone.fetch方法中放置一个断点,以查看服务器使用哪种格式以及它在哪里中断了模型的创建。

09-30 16:20
查看更多