Backbone: fetch collection from server

2019-02-12 01:39发布

I'm trying to fetch a collection from my server. I'm using version 0.3.3 (not the master from github) However I am running in this exception:

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

This is the way I created the error:

var MyModel = Backbone.Model.extend();
var MyCollection = Backbone.Collection.extend({
    url: '/api/collection',
    model: MyModel
});
var coll = new MyCollection();
coll.fetch();

The elements in /api/collection are parsed in JSON. I tried to return them in various formats

["Id1", "Id2", ... ]
[{id: "Id1, somethingElse: "..."}, ...]
{id1: { id1s content}, id2: { ... }, ...}

However the error was always the same. What is wrong with this code?

[Edit] It doesn't help to set an error via coll.fetch({error: errorFunc}); The Exception stays the same.

[Edit2] Well it seems everything works fine until collection.fetch() calls collection.refresh() with the response object. I have not overwritten any of these functions.

[Edit3] The error is in the collection.add() method and the reason is that my elements are a list of strings... My server sent them wrong.

2条回答
走好不送
2楼-- · 2019-02-12 02:13

Since you already identified that your response format is not what Backbone expect, you should override YourModel.parse function that should take the response from your server and return an array of models acceptable by the collection. Here is the snippet from 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;
},

As you can see the default function just passes data through. You would have to make it work for your response format.

P.S. id recommend placing a breakpoint in Backbone.fetch method to see what format comes from the server and where exactly it breaks the model creation.

查看更多
够拽才男人
3楼-- · 2019-02-12 02:30

instead of

["id1", "id2", ..., "idn"]

the client expects

[{"id": "id1"}, ... {"id": "idn"}]
查看更多
登录 后发表回答