Backbone:从服务器获取集合
我正在尝试从我的服务器获取一个集合。 我正在使用版本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});
设置错误没有帮助coll.fetch({error: errorFunc});
exception保持不变。
[Edit2]好吧,看起来一切正常,直到collection.refresh()
用响应对象调用collection.refresh()
。 我没有覆盖任何这些function。
[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; },
如您所见,默认函数只传递数据。 您必须使其适用于您的响应格式。
PS id建议在Backbone.fetch方法中放置一个断点,以查看来自服务器的格式以及它在何处打破模型创建。
代替
["id1", "id2", ..., "idn"]
客户期望
[{"id": "id1"}, ... {"id": "idn"}]